Home > Enterprise >  Objects are not valid as a React child, use an array instead
Objects are not valid as a React child, use an array instead

Time:05-12

I am trying to render the first and last name from a json request using axios.

I am getting the following error you see in the title. I have included a snack example here reproducing the error exactly as well as added the code below.

Thank you

const plsWork = () => {
    // Make a request for a user with a given ID
   return axios.get('https://randomuser.me/api')
      .then(({data}) => {
        console.log(data);
        return data
      })
      .catch(err => {
        console.error(err);
      });
    
    }  
    
  const userName = (userInfo) => {
    const {name: {first, last}} = userInfo;
    return {first}, {last};
  }

export default function App() {
  const [data, setData] = React.useState(' ')
  const [userInfos, setUserInfos] = React.useState([]);
  

  
  React.useEffect(() => {
    plsWork().then(randomData => {
      setData(JSON.stringify(randomData, null, 4) || 'No user data found.')
      setUserInfos(randomData.results)
    })
  }, []);

  return (
    <View>
    <ScrollView>
      {
        userInfos.map((userInfo, idx) => (
          <Text key={idx}>
            {userName(userInfo)}
          </Text>
        ))
      }
      <Text style={{color: 'black', fontSize: 15}}>
        {data}
      </Text>
    </ScrollView>
    </View>
  );
}

CodePudding user response:

You have to return a React Component in the userName function.

In the line 21: Change from return {first}, {last} to return <>{first}, {last}</>.

It should work! Here is code edited: snack expo

  • Related