Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
redux reset state when changing pages

enter image description hereSo i've implemented infinite scroll with redux. Everythings works its just that when I change pages then go back to the home page, it shows the posts i scrolled down to previously. My issue with this is that when i create a new post, it shows all the way at the bottom because its showing the previous posts i scrolled down to first then the newly created post. I've been scouring here and the only thing that sounded logical to me was to reset the state on component unmount. I've created it in my actions and added it to my useEffect and it still dont work. Is there a way when I leave my home page, it will reset so that when i go back to my home page it will fetch all posts again? Im stuck. Help please

HomePage

const [page, setPage] = useState(1);
const dispatch = useDispatch();
const { loading, posts, total } = useSelector((state) => state.posts);

useEffect(() => {
    dispatch(getPosts(page));

    return () => {
      dispatch(resetPosts());
    };
  }, [dispatch, page]);

Actions

export const getPosts = (page) => async (dispatch) => {
  try {
    const {
      data: { posts, totalPosts },
    } = await api.fetchPosts(page);

    dispatch({
      type: PC.FETCH_ALL_POSTS_SUCCESS,
      payload: { posts, totalPosts },
    });
  } catch (error) {
    dispatch({ type: PC.FETCH_ALL_POSTS_FAIL, payload: error.response });
  }
};
export const resetPosts = () => {
  return { type: PC.RESET_POSTS };
};

Reducers

export const postsReducer = (state = { posts: [] }, action) => {
  switch (action.type) {
    case PC.FETCH_ALL_POSTS_REQUEST:
      return { loading: true };
    case PC.FETCH_ALL_POSTS_SUCCESS:
      return {
        loading: false,
        posts: [...state.posts, ...action.payload.posts],
        total: action.payload.totalPosts,
      };
    case PC.FETCH_ALL_POSTS_FAIL:
      return { loading: false, error: action.payload };
    case PC.RESET_POSTS:
      return state;
    case PC.CREATE_POST:
      return { ...state, posts: [...state.posts, action.payload] };

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It looks like you are storing your redux state incorrectly. Try edited your logic where you are using the spread operator. It should probably be

return {
        loading: false,
        posts: action.payload.posts,
        total: action.payload.totalPosts,
      }

This way you are actually updating your state and not making all of your state just one big posts array. I can see what you were trying to do, but that is only really needed if you are doing your return object like

return { ...state, posts: action.payload.data } 

and need to maintain other state variables alongside the posts.

A tool that could help you debug this better in the future is the redux chrome dev tools. https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda