Oblicion A
Oblicion A

Reputation: 187

React useEffect refresh does not get value

Hej everybody

I am trying to get a hold of the hooks and useEffect but I cannot understand something. My code is this:

function RedigeraProdukter() {


    //fetches redux
    const products = useSelector(state => state.products)


    //set local states
    const [product, setProduct] = useState(
        queryString.parse(window.location.search).prod
    );

    useEffect(() => {
        setProduct(queryString.parse(window.location.search).prod);
    }, [queryString.parse(window.location.search).prod]);

supposedly when the user gets the link to this page, a prop is passed as query-string which is assign to product. I used the useEffect hook for this effect, however, if I refresh the page, the useEffect does not read the prop and product becomes undefined.

Any solution for this???

Upvotes: 2

Views: 556

Answers (2)

D10S
D10S

Reputation: 1549

try this:

useEffect(() => {
        setProduct(queryString.parse(window.location.search).prod);
    }, [window.location.search]); <-- changed

Upvotes: 0

curious_coder
curious_coder

Reputation: 2458

The dependency in useEffect should be product and not queryString.parse(window.location.search).prod .

function RedigeraProdukter() {

    //fetches redux
    const products = useSelector(state => state.products)

    //set local states
    const [product, setProduct] = useState("");

    useEffect(() => {
        setProduct(queryString.parse(window.location.search).prod);
    }, [product]);

}

Upvotes: 3

Related Questions