Skip to content

Instantly share code, notes, and snippets.

@ohnomalone
Created December 9, 2019 18:57
Show Gist options
  • Save ohnomalone/1f4139e8e258d0413884739edc65dbf8 to your computer and use it in GitHub Desktop.
Save ohnomalone/1f4139e8e258d0413884739edc65dbf8 to your computer and use it in GitHub Desktop.

Fetch, Post & Delete to an API

Fetch

Often fetch is called from componentDidMount in the main component. From there it can live in that file or often times the actual fetch lives in a differnt file. For this example fetch will be envoked in the componentDidMount method of the App.js file from a function called getIdeas()

In the App.js file componentDidMount() is setup like this:

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      ideas: [],
      isLoading: true,
      error: ''
    };
  }
  
  componentDidMount() {
    getIdeas()
      .then(ideas => this.setState({ ideas }))
      .catch(error => this.setState({
        error: error.message
      })
    );
  }
}

In the apiCalls.js file getIdeas is a function that has to be exported to work in the App.js file (DON'T FORGET TO IMPORT FUNCTIONS).

  • getIdeas() fetchecs the data, checks the response to make sure it is ok
export const getIdeas = () => {
  return fetch('http://localhost:3001/api/v1/ideas')
    .then(response => {
      if (!response.ok) {
        throw new Error('Error fetching ideas');
      }
      return response.json();
    })
    .catch(error => {
      throw Error(error.message);
    })
};

Post

Adding ideas will require data to be sent to the API as well as received from the API. This method sends one new idea back and on set state on teh way back adds it to the existing array of ideas.

First up is the App.js method

  addIdea = newIdea => {
    postIdea(newIdea)
      .then(idea => this.setState({
        ideas: [...this.state.ideas, idea]
      }))
      .catch(error => this.setState({ error: error.message }))
  }

Here is what is going on the in apiCalls.js file for postIdea()

export const postIdea = newIdea => {
  const options = {
    method: 'POST',
    body: JSON.stringify(newIdea),
    headers: {
      'Content-Type': 'application/json'
    }
  };
  
  return fetch('http://localhost:3001/api/v1/ideas', options)
    .then(response => {
      if (!response.ok) {
        throw Error('Error posting the new idea');
      }

      return response.json()
    })
    .catch(error => {
      throw Error(error.message)
    })
};

Delete

App.js file:

removeIdea = id => {
    deleteIdea(id)
      .then(ideas => this.setState({ ideas }))
      .catch(error => this.setState({ error: error.message }));
  }

apiCalls.js file:

export const deleteIdea = id => {
  const options = {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json'
    }
  }

  return fetch(`http://localhost:3001/api/v1/ideas/${id}`, options)
    .then(response => {
      if (!response.ok) {
        throw Error('Error deleting idea.')
      }
      return getIdeas();
    }).catch(error => {
      throw Error(error.message)
    });
};

Using headers:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment