Lester Arévalo
Lester Arévalo

Reputation: 462

why I'm not getting the actual state with redux?

I'm getting the state to populate my form but is not the actual state, apparently it is the initial state.

import React from "react";
import store from "../store";

const Invoice = () => {
  console.log(store.getState().login);

    return (
    <div className="span7">
      <h4 className="title">
        <span className="text">
          <strong>Datos</strong> de facturación
        </span>
      </h4>
...

However, my redux chrome DevTools is showing the actual state (the right one), why the difference? enter image description here

enter image description here

Upvotes: 0

Views: 75

Answers (2)

Aprillion
Aprillion

Reputation: 22322

Decide on 1 source of truth for your state - if you believe it should live in redux, then select the state from redux and DON'T combine it with a local useState:

import React from "react";
import { useSelector } from "react-redux";

const Invoice = () => {
  const userAuth = useSelector(state => state.login);
  console.log(userAuth);
}

Upvotes: 1

Danko
Danko

Reputation: 1864

If you want to log current state (from redux), I think you should use subscription (store.subscribe(...)) and put it into useEffect hook.

Something like this:

useEffect(() => {
  const subscription = store.subscribe(() => {
        console.log(store.getState().login);
      });
  return () => { subscription() } // clear out subscription when component unmounts
},[])

You are seeing difference between redux dev tools and your conslole.log because with store.getState() you are getting state at it was when your component was mounted. With subscribe you are getting notified any time some action get dispatched an state get changed.

Upvotes: 0

Related Questions