skip to Main Content

Can anyone explain how to initialize a value via the useState hook from the store where user information is stored? After the first rendering it returns undefined

const [lastName, setLastName] = useState<string|null>(store.user.lastName);

I’ve used useEffect. But idk how to do this without using react hooks

    useEffect(() => {
        setLastName(store.user.firstName)
    }, [store.user]);

2

Answers


  1. If your state will be always as the other variable and change accordingly to store.user.lastName, just pass it as props to the component.

    Say you have UserCard component where you have the problem

    function UserCard() {
        const [lastName, setLastName] = useState<string|null>(store.user.lastName);
        useEffect(() => {
            setLastName(store.user.firstName)
        }, [store.user]);
    
        return <>{lastName}</>
    }
    

    Then you need to refactor it to:

    function UserCard({ lastName }) {
        return <>{lastName}</>
    }
    

    and use it like <UserCard lastName={store.user.lastName} />

    Login or Signup to reply.
  2. If you’re facing the issue of undefined after the first render and you’re using useState to initialize lastName with a value from your store, it’s likely because the store’s user data isn’t populated at the time of the component’s initial render.

    In that case, you can handle it like this:

    const [lastName, setLastName] = useState(store.user.lastName);
    
    useEffect(() => {
        if (store.user.lastName) {
            setLastName(store.user.lastName);
        }
    }, [store.user.lastName]);
    
    

    In this case, any time store.user.lastName changes, the useEffect will run and update your local state with the new value.

    Now as you said "without using react hooks", so if you want to avoid hooks entirely, consider using a class component with state management in lifecycle methods like componentDidMount and componentDidUpdate.
    Here is how you can do that:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          lastName: props.store.user.lastName
        };
      }
    
      componentDidMount() {
        this.setState({
          lastName: this.props.store.user.lastName
        });
      }
    
      componentDidUpdate(prevProps) {
        if (prevProps.store.user.lastName !== this.props.store.user.lastName) {
          this.setState({
            lastName: this.props.store.user.lastName
          });
        }
      }
    
      render() {
        // ...
      }
    }
    

    Although this last one is not recommended, so try to use with hooks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search