0

I have an application in react. The state of my application is as follows

const [book, setBook] = useState({
    title: '',
    cover: {}
    numberPages: 0,
    resume: '',
    date: date,
});

Cover prop contains a file. When I try to convert the state to json (JSON.stringify(book)) to send it with FETCH, the cover property is an empty object. How can I send this information correctly?

My on submit event form

 let handleForm = (e) => {

    data = JSON.stringify(book);

    let info = {
        method: 'POST',
        body: data,
        headers: { 
            'X-CSRF-TOKEN': header,
            "Content-Type": "application/json",
            "Accept": "application/json, text-plain, */*"
         }
    }

    fetch('/books/add', info)
        .then(response => response.json())
        .then(result => console.log(result))
        .catch(error => console.log(error));

    e.preventDefault();
}
Jouio
  • 27
  • 5

1 Answers1

0

when you are sending files in fetch make sure u use the formdata

var data = new FormData()
data.append('title', book.title)
data.append('cover', book.cover)

fetch('/', {
  method: 'POST',
  body: data
})

Hope it works. If not please comment your code where you are making api call

Nikhil Ponduri
  • 409
  • 9
  • 28
  • you can find more answers [here](https://stackoverflow.com/questions/36067767/how-do-i-upload-a-file-with-the-js-fetch-api) – Nikhil Ponduri Apr 16 '20 at 04:32