Home > Software engineering >  How do I handle an API response with useState to update a state?
How do I handle an API response with useState to update a state?

Time:04-16

I am working on an API response. My aim is to take this API response to update a specified state.

Here the neccessary code snippet from my functional componenet:

const [recordImagesPayload, setRecordImagesPayload] = useState([]);

  useEffect(() => {
    const headers = { 'Content-Type': 'application/json' };
    // const payload = JSON.stringify({ ...createPayload(), recordImage: newImage });

    request(`${url}`, { headers, method: 'GET' })
      .then((response: any) => response.json())
      .then(json => {
        var obj = JSON.parse(json);
        var res: any = [];
        for (var i in obj) {
          res.push(obj[i]);
        }
        setRecordImagesPayload(res);
        console.log(res);
      });
  }, []);

My console.is not showing the res from my last line of code. I am probably doing something wrong with the response but I don't know what to do.

Please help.

Thanks in advance. :)

CodePudding user response:

I assume the request function is using fetch function, in that case you are already parsing the json response using response.json() call, so the resolved value in the next then is not json, so you don't have to use JSON.parse there

Try running this. Here instead of creating a new array and for loop, we can just use Object.values

useEffect(() => {
        const headers = { 'Content-Type': 'application/json' };
        // const payload = JSON.stringify({ ...createPayload(), recordImage: newImage });
    
        request(`${url}`, { headers, method: 'GET' })
          .then((response: any) => response.json())
          .then(result => {
            const res = Object.values(result);
            setRecordImagesPayload(res);
            console.log(res);
          });
      }, []);

CodePudding user response:

Thanks @Akhil. I had a minor issue in my code regarding Typescript which was leading to the issue. The type of the result wasn't specified, but beside that, Akhil's answer was very accurate. Many thanks for the quick response and support.

Here is the final code which worked for me:

useEffect(() => {
        const headers = { 'Content-Type': 'application/json' };
        // const payload = JSON.stringify({ ...createPayload(), recordImage: newImage });
    
        request(`${url}`, { headers, method: 'GET' })
          .then((response: any) => response.json())
          .then(result: any => {
            const res = Object.values(result);
            setRecordImagesPayload(res);
            console.log(res);
          });
      }, []);
  • Related