简体   繁体   中英

fetch json data to state array

I fetch and get the data, I want to save it to state using setState as an array or object so I can call to each field in the return part and display it on screen

but I get this error:

Uncaught Error: Objects are not valid as a React child (found: object with keys {gender, name, location, email, login, dob, registered, phone, cell, id, picture, nat}). If you meant to render a collection of children, use an array instead

import {useState} from 'react'

export default function Test(){
    const [data, setData] = useState([]);

    const getInfo = async () =>{
        const response = await fetch('https://randomuser.me/api');
        if(response.status === 200){
            const res = await response.json();
            setData(res.results[0]);
            // also try this: setData(res) 
            // also try this: setData(res.result)
        }else{
            throw new Error('Unable to fetch data')
        }
    }
    
    return(
        <div>
            <button onClick={() =>{getInfo()}}>fetch data</button>
            {data}
        </div>
    )
}

Please have a look at this codesandbox URL, I feel you can make use of useEffect for your usecase link

The problem is your are getting an response which is not an array. You are trying to use higher order array methode on a object. Use,

const resultArray = res.results;

get the array of results from the JSON.

It seems like res.results[0] is the object that has the keys of gender , name , location , email , login , dob , registered , phone , cell , id , picture , nat . But you are trying to set the state value data as an array.

You should set the data type to object.

In render function to browse the data, iterate the keys using Object.keys() .


for the onClick triggering way in render, you don't need to () => {getInfo()} since there is no specific parameters passed to the method, just use onClick={getInfo} .

import {useState} from 'react'

export default function Test(){
    const [data, setData] = useState({});

    const getInfo = async () =>{
        const response = await fetch('https://randomuser.me/api');
        if(response.status === 200){
            const res = await response.json();
            setData(res.results[0]);
            // also try this: setData(res) 
            // also try this: setData(res.result)
        }else{
            throw new Error('Unable to fetch data')
        }
    }
    
    return(
        <div>
            <button onClick={getInfo}>fetch data</button>
            {Object.keys.map(key => (<div>
               {key} : {data.key}
            </div>)}
        </div>
    )
}

The data being returned here from "https://randomuser.me/api" is not a simple JSON data. It is really a JSON object with multiple sub-objects in it such as "name", which is again having "title", "first" and "last" as sub-objects. This is the reason you are getting error that "found: object with keys".

If you are looking for dummy data for testing purpose, I would suggest you to check "https://jsonplaceholder.typicode.com/", which is a good source of dummy JSON data.

I have updated your code as under, which is returning data in proper JSON format and can be assigned to state.

  const getInfo = async () =>{
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    
    if(response.status === 200){
        const res = await response.json();
        console.log(res)
        setData(res);        
    }else{
        throw new Error('Unable to fetch data')
    }
}

Your problem might be that you are using setData(res.results[0]);

I bet that this is an Object and not an Array.

const [data, setData] = useState([]);

states that the setData function only stores arrays.

try using

const [data, setData] = useState({});

and see if that is working

if it is not working give us the ouput of console.log(res.results) and console.log(typeof(res.results[0]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM