score:0
You are trying to save allusers
to the localStorage
right after setAllUsers()
but setState
is asynchronous. The value does not have to be updated on the next line. You can read more about it at reactjs.org, Why is setState giving me the wrong value?.
I would recommend to use useEffect
.
const add=()=> {
setAllusers([... allusers ,newuser])
}
useEffect(()=>{
// this is called only if the variable `allusers` changes
// because I've specified it in second argument of useEffect
localStorage.setItem('users',JSON.stringify(allusers))
}, [allusers]);
score:0
you are adding only one new user while clicking on add button. You need to copy previous data also when setting all users.
Second thing setting state is async and hence your localStorage and allusers may have different value and to avoid this one you need to use useEffect to set the value.
const add = ()=>{
setAllusers([...allusers ,newuser])
setID(id+1); // increase id by 1
}
useEffect(() => {
localStorage.setItem('users',JSON.stringify(allusers))
},[allusers])
score:0
()=>handleChange
is a function that takes no arguments and returns the handleChange
function. You probably want () => handleChange()
, which would take no arguments and INVOKE handleChange.
score:1
There were a lot of syntactical errors and use of functions like save
which was never declared and still used.
I rewrote the whole example and made it a bit modular so that you can comprehend it better.
Here is the working example:
Final Output:
Full Source code:
import React, { useState, useEffect } from "react";
import "./style.css";
const App = () => {
const [allusers, setAllusers] = useState([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const handleName = e => {
setName(e.target.value);
};
const handleEmail = e => {
setEmail(e.target.value);
};
const save = e => {
e.preventDefault();
let newUsers = {
id: Math.floor(Math.random() * 100000),
name: name,
email: email
};
localStorage.setItem("users", JSON.stringify([...allusers, newUsers]));
setAllusers(allusers.concat(newUsers));
console.log("Localstorage:", JSON.parse(localStorage.getItem("users")));
};
useEffect(() => {
console.log("Localstorage:", JSON.parse(localStorage.getItem("users")));
if (localStorage.getItem("users")) {
setAllusers(JSON.parse(localStorage.getItem("users")));
}
}, []);
return (
<div>
<form>
<input type="text" name="user" onChange={handleName} />
<input type="text" name="email" onChange={handleEmail} />
<button onClick={save}>Save</button>
<p>{JSON.stringify(allusers)}</p>
</form>
</div>
);
};
export default App;
As You inquired in the comment section, here is how you can implement the Update functionality:
Final Output:
Full source code:
import React, { useState, useEffect } from "react";
import "./style.css";
const App = () => {
const [allusers, setAllusers] = useState([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [id, setId] = useState(null);
const handleName = e => {
setName(e.target.value);
};
const handleEmail = e => {
setEmail(e.target.value);
};
const save = e => {
e.preventDefault();
let newUsers = {
id: Math.floor(Math.random() * 100000),
name: name,
email: email
};
localStorage.setItem("users", JSON.stringify([...allusers, newUsers]));
setAllusers(allusers.concat(newUsers));
console.log("Localstorage:", JSON.parse(localStorage.getItem("users")));
};
const setForUpdate = user => {
setName(user.name);
setEmail(user.email);
setId(user.id);
};
const update = e => {
e.preventDefault();
let modifiedData = allusers.map(user => {
if (user.id === id) {
return { ...user, name: name, email: email };
}
return user;
});
setAllusers(modifiedData);
localStorage.setItem("users", JSON.stringify(modifiedData));
setId(null);
};
useEffect(() => {
console.log("Localstorage:", JSON.parse(localStorage.getItem("users")));
if (localStorage.getItem("users")) {
setAllusers(JSON.parse(localStorage.getItem("users")));
}
}, []);
return (
<div>
<form>
<input value={name} type="text" name="user" onChange={handleName} />
<input value={email} type="text" name="email" onChange={handleEmail} />
<button disabled={!(id == null)} onClick={save}>
Save
</button>
<button disabled={id == null} onClick={update}>
Update
</button>
</form>
{allusers &&
allusers.map(user => (
<div className="userInfo">
<p>{user.name}</p>
<p>{user.email}</p>
<button onClick={() => setForUpdate(user)}>
select for update
</button>
</div>
))}
</div>
);
};
export default App;
You can find the working example here: Stackblitz
Source: stackoverflow.com
Related Query
- Local storage not updating React
- react app local storage is not setting up
- React multiple callbacks not updating the local state
- Storing layout for my react app in local storage not working
- Local Storage values not getting loaded in React App
- REACT state from local storage not loading
- Local storage not storing the last added or deleted item to/from state in React app
- Component local state not updating with react custom hooks
- Axios instance not getting the token from the Local storage on the first attempt || React JS
- React - Digit 0 is not saved to local storage all other digits are kept in sync
- Height not returned from local storage when refreshing react grid layout
- State not updating when using React state hook within setInterval
- React setState not updating state
- React Child Component Not Updating After Parent State Change
- React setState not Updating Immediately
- React Routing works in local machine but not Heroku
- React component not updating when store state has changed
- React hooks useState not updating with onChange
- React context not updating
- Why is my react component not updating with state updates?
- React Mobx - component not updating after store change
- React Native: setState not updating immediately when logging in console
- React Router V4 is updating URL, but not refreshing (React, Redux)
- React Context Api vs Local Storage
- React context useReducer is not updating correctly
- Props not updating when redux state change in React Hooks
- How to fix React Router component not updating as route changes
- Component not updating when I change the props that I pass to it in React
- react props not updating with redux store
- setState not working for updating an array in React
More Query from same tag
- MaterialUI card view not showing
- Property 'location' does not exist on type 'typeof window'
- How to generate unique ids in react. js component
- How to dynamically change page title and description in ClojureScript / Reagent
- ReactDOM is not defined ( but from within a React method )
- React state update from Redux causing Maximum update depth exceeded error
- From Google Sheets into React Grid
- Select just one row in ant-design table component
- Code splitting application sections via dynamic imports
- Animate text with React (typing effect)
- How do I refresh React state after running navigator.pop()?
- Exporting asyc dependent, non-async const from JS module
- Does ReactDOM.render wait for the document to be loaded before rendering?
- Not Being Able To Retrieve My Data From Firebase V9
- How to add scroll bar to a react component?
- Creating a header in React
- Uncaught TypeError: color is undefined || MUI Button & CreateTheme Issue
- Render unique divs for each hovered element
- Fetch Rick and Morty API
- React - how to show the difference between the current and next props?
- non empty array with length=0 in Meteor
- Jest + Enzyme testing error in mapStateToProps()
- How do I setup routes for two React apps using dotnet core 3.1?
- How to avoid JSX component from condensing when React.js rendering it?
- How to deal with UseEffect running multiple times due to retrieval from Firestore DB?
- react-hook-form Set error message for custom validation when using useController
- In React, how can I use children?
- I am having problem using http-proxy-middleware
- Is it possible to create different action button in mui tables?
- Trying to print the state in my landing page