I have this code to get the user input and send it back to the dispatch
import React, { useState } from 'react';
export default function Form(props) {
const [book, setBook] = useState({
title: '',
author: '',
});
const onChange = (e) => {
if (book[e.target.name] !== e.target.value) {
setBook({
...book,
[e.target.name]: e.target.value,
});
}
};
const { add } = props;
return (
<form>
<input onChange={onChange} type="text" name="title" placeholder="Title" />
<input onChange={onChange} type="text" name="author" placeholder="Author" />
<button type="button" onClick={add(book.title, book.author)}>Add Book</button>
</form>
);
}
The add function is this:
const submitBookToStore = (title, author) => {
const newBook = {
id: uuidv4(),
title,
author,
};
dispatch(addBook(newBook));
};
Then I see this error:
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
The strange behaviour is it calls onClick when the page is loaded when I did not clicked!!
If you call it like this:
onClick={add(book.title, book.author)}
It will run on render. Try this instead:
onClick={() => add(book.title, book.author)}
That is because add() indicates a function call where as in your onChange, you are just giving a function to be called onChange={onChange} the difference lies in the parentheses ()
Try the following:
import React, { useState } from 'react';
export default function Form(props) {
const { add } = props;
const [book, setBook] = useState({
title: '',
author: '',
});
const onChange = (e) => {
if (book[e.target.name] !== e.target.value) {
setBook({
...book,
[e.target.name]: e.target.value,
});
}
};
const handleAdd = () => { add(book.title, book.author) }
return (
<form>
<input onChange={onChange} type="text" name="title" placeholder="Title" />
<input onChange={onChange} type="text" name="author" placeholder="Author" />
<button type="button" onClick={handleAdd}>Add Book</button>
</form>
);
}
Hopefully that helps