2

new to react here. I am now trying to do a post through an API by following this previous stack overflow post React: Fetch DELETE and PUT requests. And here is my code:

 submitHandler = (event) => {
    const state = this.state.newClient
    this.setState({creating: false, submitable:false});
    this.resetNewClient();
    event.preventDefault();
    const formData = new FormData();
    formData.append('slug', state.slug);
    formData.append('name', state.name);
    formData.append('description', state.description);
    return fetch('https://reqres.in/api/users', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then((json) => {
    console.log('success')
    })
}

If it is wrong please correct my code. The submitHandler is triggered by a button, and the newClient is an array that contains a slug, name, and description. However, what I to know other than whether my code is correct or not is how to check if the data is properly posted in the API. In case it is necessary here is the componentDidMount that fetches the data.

componentDidMount() {
    fetch("https://reqres.in/api/users?page=3")
    .then(data => data.json())
    .then(datum => {
        const results = datum.data.map(x => {
        return {
          slug: x.id,
          name: x.first_name,
          description: x.last_name
        }
    })
    this.setState({ clients: results });
    });
}

If there is a better way to have done this I would also like to know. Thanks

XXX
  • 47
  • 9
  • Open your developer tools and check the network panel if the request is sent, and its response? – ChrisR Jun 25 '18 at 07:49

1 Answers1

0

I usually construct a JavaScript object and do JSON.stringify for posting data.

const postData = {
  slug: state.slug,
  name: state.name,
  description: state.description
};
return fetch('https://reqres.in/api/users', {
  method: 'POST',
  body: JSON.stringify(postData)
})
vijayst
  • 20,359
  • 18
  • 69
  • 113
  • My main question was how to check, but this does indeed look nicer and easier to unerstand. – XXX Jun 25 '18 at 02:33