Reputation: 469
I have an api that returns this json below, what I'm trying to do is that I just take the "name" that json returns and put it in a text component. I've tried to do it but it returns null or full json.
{
"user": {
"_id": "1",
"name": "User Name",
"email": "[email protected]",
}
}
const [cars, setCars] = useState([]);
async function loadCars() {
const response = await api.get('me');
setCars(response.data);
}
Upvotes: 0
Views: 486
Reputation: 36
Since some of the code is abstracted I'm assuming that 'response.data' is the JSON object you posted above? If so you could simply change setCars
from the response.data
value to the field that you're looking to capture in state
As in:
async function loadCars() {
const response = await api.get('me');
setCars(response.data.user.name);
}
In this example you're also initializing state to an empty array, so you might consider aligning it with it's future value and either using useState("")
or useState(null)
so that your conditional rendering is based on if state has a string with a value, or is simply no longer null. Either way it's not relevant in regards to your true question.
More on hooks here: https://reactjs.org/docs/hooks-intro.html
Upvotes: 1