Trying to make a fetch in a class

Viewed 84
import React, { Component, Fragment, useEffect, useState } from "react";
import Select from "react-select";
import { useHistory } from "react-router-dom"; 

const options = [
  { value: "red", label: "red" },
  { value: "blue", label: "blue" },
  { value: "green", label: "green" }
];

export default class CrearPost extends Component {
  state = {
    selectedOption: null
  };
  handleChange = selectedOption => {
    /*I added all this*/ 
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

    const PostData = () => {
      fetch('/createpost', { /*This route is in my nodejs server*/ 
        method:'post',
        headers:{
          'Content-Type':'application/json',
          Authorization: "Bearer " + localStorage.getItem("jwt")
        },
        body:JSON.stringify({
          title,
          body
        })
      }).then(res=>res.json())
      .then(data=>{
        console.log(data)
        if(data.error){
          alert(data.error)
        }
        else{
          alert('Post created')
          history.push('/')
        }
      }).catch(err=>{
        console.log(err)
      })
    }
  };
  render() {
    return (
      <div align="center">
      <Fragment>
        <Select
          className="basic-single"
          classNamePrefix="select"
          defaultValue={options[0]}
          isDisabled={false}
          isLoading={false}
          isClearable={true}
          isRtl={false}
          isSearchable={true}
          name="color"
          options={options}
          value={title}/*I added this*/ 
          onChange={(e) => setTitle(e.target.value)}/*I added this*/ 
        />
      </Fragment>
      <input
        type="text"
        placeholder="body"
        value={body}/*I added this*/ 
        onChange={(e) => setBody(e.target.value)}/*I added this*/ 
      />
      <button onClick={() => PostData()}/*I added this*/>
        Submit post
      </button>
      </div>
    );
  }
}

I tried to make fetch but I get an error, In PostData array function but I am getting the error maybe in that part. Even I tried to make the fetch as is it were a function, but this doesn't work. And in buttons I call PostData function because is there where I have the fetch the error is the next:

Error picture

2 Answers

You can try to change:

 const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

into this

state = {
    selectedOption: null,
    title: "",
    body: ""
  };

Related