0

I want to fetch data from a different Server with a REST API.

I do this:

    return fetch('http://localhost:9000/processes')
        .then((response) => response.json())
        .then((responseJson) => {
            return responseJson;
        })
        .catch((error) => {
            console.error(error);
        });

In the render function I have this:

       {JSON.stringify(getProcesses().Prozess1) }

and this

        {JSON.stringify(getProcesses()) }

no one of thesse two examples returns something

The rest API should return this:

{
  "Prozess1": "Hallo ich bin ein Prozess"
}

whats my problem in this case

3
  • getProcesses() is that asynchronous action which returns a promise? Commented Apr 10, 2017 at 14:33
  • Yes getProcesses ist the Funktion which shoukd Return the json Commented Apr 10, 2017 at 14:40
  • fetch() is async so it shouldn't return anything. fetch().then() is a promise, which means whenever fetch completes, do the following. So refactor your code a bit Commented Apr 10, 2017 at 14:43

1 Answer 1

3

React render() is a pure function of state and props. You shouldn't try to perform asynchronous API calls or modify state inside render; so if you need to use fetched data in your components, you can either load it in the parent component and pass it as props, or perform the fetch inside the component and save the result in your component state.

Here's an example of a possible, simplified implementation using the component state:

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.getProcesses = this.getProcesses.bind(this);
  }

  componentDidMount() {
    this.getProcesses();
  }

  async getProcesses() {
    try {
      const response = await fetch('http://localhost:9000/processes');
      if (response.ok) {
        const processes = await response.json();
        this.setState({processes}); //this will trigger the render function with the new state
      } else {
        console.error(response.status);
      }
    } catch(e) {
      console.error(e);
    }
  }

  render() {
    const {processes} = this.state;
    return (
      <Text>
        {processes && processes.Prozess1}
      </Text>
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.