i have to get some data from a complex objects json (in my case is: valor_custo_fornecedor from the detalhe object, how can i do this ?
i already tried with axios like this:
const [valorCusto, setValorCusto] = useState([]);
useEffect(() => {
axios.get('MY API LINK').then((res) => {
let valor = res.detalhe.valor_custo_fornecedor;
setValorCusto(res.valorCusto.valor_custo_fornecedor);
});
});
4
Answers
After setting response in setValorCusto ; you can loop over you state variable and get the desired value
Like the other answers state. What you are returning from your API is an array of objects. Currently in your code, that array lives inside the response object. So in this snippet below:
You need to specify from which item in the array you would like to get the detalhe object from (like res[0].detalhe).
One way you could do if you like to use everything from the array, is to store the entire array in your useState. Afterwards, you could loop over the array and do something with the objects inside of it.
PS. If you’re not entirely sure what the state holds. You could log it to the page by doing something like
<div>{JSON.stringify(valorCusto)}</div>
You can convert json like this:
It is hard to tell without seeing the complete json what key/value pairs exist in the data, but from what I can see you are passing a value that does not seem to exist in the data to
setValorCusto
, namely:res.valorCusto.valor_custo_fornecedor
I am guessing what you want to pass to
setValorCusto
is thevalor
variable that you have defined above? However theres.data.detalhe
is as others have replied an array, which you would either have to iterate through or specify an index for.Another detail, not relating to the question in itself, is that I would add a dependency array to the effect, so that this api request is not called on every component re-render. So the end result would look something like this:
Notice the empty array as the second parameter in the
useEffect
call. This means that the effect will only be run on the initial rendering of the component.Then you can access the value by simply using
valorCusto
wherever you need it in the component.