0

I cannot display a property of my JSON (DataUser.name.first)

` import React, {useEffect,useState}from 'react'; import Article from '../components/Article'; import '../styles/containers/Home.scss'; const Home = () => { const [DataUser, setDataUser] = useState("Cargando"); useEffect(() => { const Cargar = async () => { let respuesta = await fetch(`https://randomuser.me/api/`); let respuestaJSON = await respuesta.json(); setDataUser(respuestaJSON.results[0]); }; Cargar(); }, []); return ( <> <div className='Home'> {console.log(DataUser.gender)} /*:)*/ {console.log(DataUser.name.first)} /*:(*/ </div> </> ); }; export default Home; ` 

I'm trying to pass properties to a component in react, when I pass the cell number everything is ok. But when I try to pass the name I get an error.

My JSON "results": [ { "gender": "male", "name": { "title": "Mr", "first": "Elliot", "last": "Thompson" }, }, ],

I want to get the value that is inside name. The problem that I see is that we have an object inside another object. and not an array inside an object.

6
  • Why don't you pass DataUser.name.first (instead of DataUser.name which is an object and not a string) to Article? Commented May 18, 2020 at 1:45
  • yes: this is the JSON. I just want to get the data from (first) "name": { "title": "Mr", "first": "Alex", "last": "Blanco" }, Commented May 18, 2020 at 1:54
  • <Article cell={DataUser.cell} name={DataUser.name.first}/> ? Commented May 18, 2020 at 1:55
  • I add the component code "Articulo" Commented May 18, 2020 at 2:06
  • I think that the .map function does not work, because I only want the property (name.first) Commented May 18, 2020 at 2:09

1 Answer 1

0

I think the problem is in your Article component, check how you handle name prop.

You should treat it as an object:

DataUser.name = { "title": "Miss", "first": "Zenóbia", "last": "da Paz" } 

Or you can also pass one of the keys: title, first, last

<Article cell={DataUser.cell} name={DataUser.name.first}/> 

If you can't resolve this, attach the component code.

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

3 Comments

I add the component code "Articulo"
// check DataUser object before render if (!DataUser) { return null; }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.