in a form tag the input show [object Object] at first render instead of placeholder (it use the value attribute)

Viewed 35

This is the BookForm.js it is a component that use react context api , this component return a form that contain of 3 input tag

import React, { useContext, useState } from 'react';
import { BookContext } from '../contexts/BookContext';
/* ________________________________________________________________ */
const BookForm = () => {
  const { dispatch } = useContext(BookContext);
  const [title, setTitle] = useState(BookContext);
  const [author, setAuthor] = useState(BookContext);

  const handleSubmit = (e) => {
    e.preventDefault();
    // console.log(title, author);
    dispatch({ type: 'ADD_BOOK', book: { title, author } });
    // addBook(title, author);
    setTitle('');
    setAuthor('');
  };
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="book title"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        required
      />

      <input
        type="text"
        placeholder="author"
        value={author}
        onChange={(e) => setAuthor(e.target.value)}
        required
      />
      <input type="submit" value="add book" />
    </form>
  );
};

export default BookForm;

The output is This is the output view

the below codebox is BookContext.js that is a stateless function for providing book data and dispatch function and there is a useEffect hook to storing data of new books :

import React, { useReducer, createContext, useEffect } from 'react';
import { bookReducer } from '../reducers/bookReducer';
/* ________________________________________________________________ */
export const BookContext = createContext();
/* ________________________________________________________________ */
const BookContextProvider = (props) => {
  const [books, dispatch] = useReducer(bookReducer, [], () => {
    const localData = localStorage.getItem('books');
    return localData ? JSON.parse(localData) : [];
  });

  useEffect(() => {
    localStorage.setItem('books', JSON.stringify(books));
    localStorage.getItem('books');
  }, [books]);
  /* ________________________________________________________________ */
  return (
    <BookContext.Provider value={{ books, dispatch }}>
      {props.children}
    </BookContext.Provider>
  );
};

export default BookContextProvider;

0 Answers
Related