0

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>
  );
}
2
  • 1
    well, i mean, you returned an object, rather than a component to render. If you want to render a string you could just return a string. Commented May 11, 2022 at 15:10
  • 1
    Does this answer your question? Objects are not valid as a React child Commented May 11, 2022 at 15:13

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Plain string: return first + " " + last would also work since the questioner uses a Text component as a parent.
or template strings could be suffice as well ?
@DavidScholz You're right, but I still suggest using Fragments, It resolves every problem like that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.