Reputation: 479
searchInput
.searchInput
Change field searchInput
I implement in method upadateStateSearchInput
in file Home.js.
But I have error:
TypeError: Cannot read property 'map' of undefined
in Table.js in this line:
<tbody className="table-body">
{props.dataAttribute.map(item => (
const Home = () => {
const [value, setValue] = useState({
listCategory: [],
searchInput: ""
});
useEffect(() => {
async function fetchData(searchInput ) {
const res = await apiCategory('api', {method: 'GET'}, searchInput);
setValue(prev => ({
...prev,
listCategory: res.data,
}));}
fetchData(value.searchInput);
}, []);
const upadateStateSearchInput = (event) =>{ //THIS METHOD
setValue({
searchInput: event.target.value
});
};
return (
<div>
<Search value={value.searchInput}
userEnteredValue={upadateStateSearchInput}
outputInConsoleNewState={() => console.log(value.searchInput)}
/>
<Table dataAttribute={value.listCategory} />
</div>
);
};
export default (props) => (
<table className="table">
<thead className="table-head">
<tr>
<th onClick={props.changeSortAscDesc}>ID <small>{props.sortAscDesc}</small></th>
<th>TITLE</th>
</tr>
</thead>
<tbody className="table-body">
{props.dataAttribute.map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.title}</td
</tr>
))}
</tbody>
</table>
);
export default ({ value, userEnteredValue, outputInConsoleNewState}) => {
return (
<div className="search">
<input type="text" onChange={userEnteredValue} value={value}/>
<button onClick={() => outputInConsoleNewState(value)}>Search</button>
</div>
);
};
P.S.Also i tried to change the upadateStateSearchInput
method like this:
const upadateStateSearchInput = (event) =>{
setValue((prev) => ({
...prev,
searchInput: event.target.value
}));
};
But then error:
TypeError: Cannot read property 'value of null'
In Home.js in this line:
searchInput: event.target.value
Upvotes: 0
Views: 84
Reputation: 1292
You are setting store like this.
const [value, setValue] = useState({
listCategory: [],
searchInput: ""
});
Your onchange is setting listCategory
to undefined. .map
of undefined
is throwing error. In order to code on safe side, please start using optional chaining.
const upadateStateSearchInput = (event) => { //THIS METHOD
setValue({
searchInput: event.target.value
});
};
Upvotes: 0
Reputation: 4987
You probably need to change :
const upadateStateSearchInput = (event) =>{ //THIS METHOD
setValue({
searchInput: event.target.value
});
};
By:
const upadateStateSearchInput = (valueFromInput) =>{ //THIS METHOD
setValue({
...value, // keep your state as it is
searchInput: valueFromInput // And just change searchInput as you did before
});
};
In your Home component.
I think the value given to your method upadateStateSearchInput
is the value entered by the input.
Upvotes: 2