I
I
Ivan Sharkov2022-02-14 18:32:43
React
Ivan Sharkov, 2022-02-14 18:32:43

useEffect stopped working on page load after connecting json-server?

When the data was on a local file in db.json without using json-server , everything worked, the data came through Axios and was dispatched to Redux, from there they were received by useSelector in the Home component and everything worked. But when I connected and configured the json-server, the data stopped coming, although the server itself works on the set port, and if you look using window.test (), then the data comes, but for some reason they stopped when the page was loaded in useEffect get into the state (useEffect itself stopped working when the page loads). The data does not reach the required Home component. What to do?

Code for receiving data from the server (+ test for receiving data):

const dispatch = useDispatch();

  React.useEffect(() => {
    Axios.get('http://localhost:3001/pizzas').then(({ data }) => { dispatch((setPizzasAction(data))) }); 
  }, [])

  window.test = () => {
    Axios.get('http://localhost:3001/pizzas').then(({ data }) => {
      console.log(data)
      dispatch((setPizzasAction(data)))
    });
  }


The code of the Home component , where the data from the redux should be transferred (here the state does not already contain the necessary data):
const dispatch = useDispatch();

  const { items } = useSelector((state) => {
    return {
      items: state.pizzas.items,
    };
  });

  const onSelectCategory = React.useCallback((index) => {
    dispatch(setCategory(index));
  }, []);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question