Search code examples
reactjsredux

POST https://us-central1-bookstore-api-e63c8.cloudfunctions.net/bookstoreApi/apps/dXhbHW84R2UylfqfKuq7/books 400


New to react here. I'm getting this error: xhr.js:210 POST https://us-central1-bookstore-api-e63c8.cloudfunctions.net/bookstoreApi/apps/dXhbHW84R2UylfqfKuq7/books 400 and I don´t know why. I checked all over StackOverflow, but couldn't find a good answer from similar questions.

I have the Add button, but for some reason this error happen only in that button, i already check the Api and it works on other projects, but in mine it can remove and edit but when i going to create a new book i have this error

import axios from 'axios';
import { getBooks, addBook, removeBook } from '../redux/books/books';

export default class BookstoreAPI {
  static #BASE_URL = 'https://us-central1-bookstore-api-e63c8.cloudfunctions.net/bookstoreApi';

  static #APP_ID = 'dXhbHW84R2UylfqfKuq7';

  static addBooktoAPI = (book) => async (dispatch) => {
    const url = `${this.#BASE_URL}/apps/${this.#APP_ID}/books`;
    const {
      id, title, author, category,
    } = book;
    const APIbook = {
      item_id: id,
      category,
      title: `${title} - ${author}`,
    };
    await axios.post(url, APIbook);
    dispatch(addBook(book));
  };

  static deleteBookFromAPI = (id) => async (dispatch) => {
    const url = `${this.#BASE_URL}/apps/${this.#APP_ID}/books/${id}`;
    const body = {
      item_id: id,
    };
    await axios.delete(url, body);
    dispatch(removeBook(id));
  };

  static getAllBooksFromAPI = () => async (dispatch) => {
    const url = `${this.#BASE_URL}/apps/${this.#APP_ID}/books`;
    const response = await axios.get(url);
    const books = [];
    Object.entries(response.data).forEach(([id, info]) => {
      const { title: APItitle, category } = info[0];
      const [title, author] = APItitle.split(' - ');
      const newBook = {
        id,
        title,
        category,
        author,
      };
      books.push(newBook);
    });
    dispatch(getBooks(books));
  };
}

this is my API Store, and i know the error is here but i can´t figure out were is it.


Solution

  • I have verified your API and it's returning an error saying 'author' is required. Just add author key to your payload and try.

    static addBooktoAPI = (book) => async (dispatch) => {
        const url = `${this.#BASE_URL}/apps/${this.#APP_ID}/books`;
        const {
          id, title, author, category,
        } = book;
        const APIbook = {
          item_id: id,
          category,
          author
          title: `${title} - ${author}`,
        };
        await axios.post(url, APIbook);
        dispatch(addBook(book));
      };