Search code examples
javascriptreactjsjsonfetch-apigatsby

How to get values of the first element of fetch reponse


I try to get values of the first element of my fetch request.

Here you can see my code -> the result of the fetch-request is assigned to "data" variable.

const ListRezept = (props) => {
   const url_id = props.params.id;
   const [data, setData] = useState(null);
   const [isPending, setIsPending] = useState(true);
   const [error, setError] = useState(null);
  
   useEffect(() => {
    const abortCont = new AbortController();

    setTimeout(() => {
    fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezept?$filter=RezeptId eq '+ url_id)
       .then(res => {
          if (!res.ok) { // error coming back from server
            console.log("error");
            throw Error('Could not fetch the data for that resource!');
          } 
          return res.json();
       })
       .then(data => {
        setIsPending(false);
        setData(data.value);
        setError(null);
       })
       .catch(err => {
        if (err.name === 'AbortError') {
          console.log('fetch aborted')
        } else {
          // auto catches network / connection error
          setIsPending(false);
          setError(err.message);
        }
       });
 }, []);

     // abort the fetch
     return () => abortCont.abort();
 }, []) 
 }

The structure of the returned data.value (after json()-Parsing) you can see here structure of parsed data.value

How can I assign the first element of returned "json()" value to an variable? Later on I want to pass this "data" variable to another page and work with these values in gatsby.

Pseudocode:

// assign first element to a variable
const aenderungsdatum = data[0].aenderungsdatum

Solution

  • Your problem is apparently this piece of code:

           .then(data => {
            setIsPending(false);
            setData(data.value);
            setError(null);
           })
    

    The third line has to be setData(data.data.value). And it will become clearer, if you rename the lambda parameter to something like json:

           .then(json => {
            setIsPending(false);
            setData(json.data.value);
            setError(null);
           })
    

    Additional problem: Your object has no property value according to the screenshot provided. So the final code should look like this:

           .then(json => {
            setIsPending(false);
            setData(json.data);
            console.log(`last change: ${json.data[0]['Aenderungsdatum']`);
            setError(null);
           })