I am trying to get a state from context and initialize to new state. But the newly created state is not initializing. Help me out.
import { ProductsContext } from "../../../store/ProductsContext";
const EditVariant = () => {
let { id } = useParams();
const navigate = useNavigate();
const { getProductsById, singleProduct } = useContext(ProductsContext);
const [productName, setProductName] = useState(singleProduct.productName);
console.log(productName) // This is undefined
useEffect(() => {
getProductsById(id);
}, []);
return (
<Form
productName={productName}
setProductName={setProductName}
/>
</div>
);
};
export default EditVariant;
The Form component gets the undefined value. The value is not initializing properly.
CodePudding user response:
You need to export your UserContext so it can be imported into the components that need it:
export const UserContext = React.createContext();
function App() {
const [name, setName] = useState('Name');
return (
<UserContext.Provider value={{ name, setName }}>
<Home />
</UserContext.Provider>
);
}
Afterward, you can import it into your desired component:
import { UserContext } '../../App'
function Home() {
const user = useContext(UserContext);
return (
<>
<label>Your name:</label>
<input type='text' onChange={e => user.setName(e.target.value)} />
<p>{user.name}</p>
</>
)
}
CodePudding user response:
useState is asynchrounous. use useEffect
to see the updated values
useEffect(() => {
console.log(productName)
}, [productName])
CodePudding user response:
It might be because singleProduct.productName was undefiend in initial and get value later so you can simply set that in useEffect like this:
const { getProductsById, singleProduct } = useContext(ProductsContext);
const [productName, setProductName] = useState();
useEffect(() => {
if(singleProduct.productName){
setProductName(singleProduct.productName)
}
},[singleProduct])