Axios Response Data not saved in State

Viewed 541

I have a custom hook useServerStatus that fetches from a RESTful API with axios. Checking the network tab, the response went through fine, I can see all my data. Using console.log to print out the result or using debugger to check the result in the browser works flawlessly. However, calling the setState method that I get from useState will not save the response data.

ServerStatus Interface (ServerStatus.ts)

interface ServerStatus {
  taskid: string
  taskmodule: string
  taskident?: string
  status: string
  server: string
  customer: string
}

useServerStatus Hook (useServerStatus.ts)

export default function useServerStatus() {
  const [serverStatus, setServerStatus] = useState<ServerStatus[][]>([]);

  useEffect(() => {
    fetchServerStatus();
  }, []);

  const fetchServerStatus = () => {
    axios.get<ServerStatus[][]>(`${config.apiURL}/servers`)
      .then(res => setServerStatus(res.data));
  }

  return serverStatus;
}

Network Tab

https://i.imgur.com/cWBSPVz.png

The first request you see in the network tab is handled the same exact way, no problems there.

React Developer Console

https://i.imgur.com/YCq3CPo.png

3 Answers

Try

const fetchServerStatus = () => {
    axios.get<ServerStatus[][]>(`${config.apiURL}/servers`)
      .then(res => { setServerStatus(res.data) });
}

So, to answer my own question:

I figured out that the problem wasn't about data not being saved in state, but data not correctly being received by axios.

I fixed it with a workaround. Instead of returning a ServerStatus[][] in my backend, I returned a ServerStatus[]. I was able to use this data instead.

Following the lesson here https://reactjs.org/docs/hooks-custom.html the most obvious thing that jumps out to me is that you aren't returning the state variable serverStatus in your code vs. the example is returning "isOnline". Try to match this by returning serverStatua in your custom effect to see if it helps.

Related