-1

I'm trying to use data from API in my react component:

let request = new XMLHttpRequest()
let output = []

request.open('GET', 'http://localhost:3005/products/157963', true)
request.onload = function() {
let data = JSON.parse(this.response)
output.push(data);
  if (request.status >= 200 && request.status < 400) {
  console.log(output[0].brand);
} else {
  console.log('error');
}
}

request.send()

const item_box = (
<ItemPanel>
  <ItemBox>
    <BoxTitle>{output[0].brand}</BoxTitle>
   </ItemBox>
   <BoxImg src={require("./ucfnti1.jpg")} alt='img error'></BoxImg>

);

and the problem is that (output[0].brand) element is rendered empty, while

console.log(output[0].brand);

prints the correct value in console :/

1 Answers1

0

you need to add this variable to state and update it when get response from your server

in your component you need: 1) set the state with 'output'

this.state = {
  output: []
}

2) update the state when get a response

request.open('GET', 'http://localhost:3005/products/157963', true)
request.onload = function() {
let data = JSON.parse(this.response)
this.setState(prevState => ({output: [...prevState.output, data]}))

3) render a value from your state

<ItemPanel>
  <ItemBox>
    <BoxTitle>{this.state.output[0].brand}</BoxTitle>
   </ItemBox>
   <BoxImg src={require("./ucfnti1.jpg")} alt='img error'></BoxImg>
Max
  • 781
  • 7
  • 19
  • Thanks, I came up with this: https://codepen.io/anon/pen/KLOOmV but I'm having problem with rendering it with my other components, I would appreciate some hint here if u dont mind. Cant even see if it is working now :/ – Wiktor Kisielewski Jun 09 '19 at 14:56