Search code examples
reactjspromisefetch-api

setState inside promise not updated


Why will the render function not update the state? See comments in code. Inside the code I have a static comment out version, this works, but the dynamic function get(..) doesn't update the State for the render function.

import React, { Component } from 'react';
import Products from "./components/products";

import './App.css';

//function App() {
class App extends Component {

  state = {
    products: [],
  }

  componentDidMount() {
    const productsURL = 'http://wundp.192.168.43.67.xip.io/rest/products';


    const get = (url, key) => {
      fetch(url)
          .then(res => res.json())
          .then((data) => {
            /* this works and i see the data */
            console.log('1: ', data[key]);
   
            /* the state is not updated, why?  */
            this.setState({ key : data[key] })
          })
          .catch(console.log)
    }

    /* this fails, the state in the render function is later empty, why?  */
    get(productsURL, 'products');

    /* this works!
    fetch('http://wundp.192.168.43.67.xip.io/rest/products')
        .then(res => res.json())
        .then((data) => {
          console.log(data);
          this.setState({ products: data.products })
        })
        .catch(console.log)
    */
  }

  render() {
    /* this.state.products is empty, why?  */
    console.log('state: ',this.state.products);

    return  (
        <Products products={this.state.products} />
    );
  }

}

export default App;

Solution

  • Thanks for Feedback. Your Solution doesn't work. It would give this error, because i don't use typescript. Line 13: 'int' is not defined

    I found a solution, i have to wrap the key with []... this.setState({ [key] : data[key] })

    then it works :-)