New To React Hook useState Is Returning Undefined
To set initial state properly you should pass it to the useState
as an argument, so:
const [notifications, setNotifications] = useState([]);
Also no matter if you set props.notifications
outside somewhere or not, but if you rely on it having some kind of default value in the component, then you should set it right there, e.g.:
const Notifications = ({ notifications = [] }) => {
And the last but not the least, using array in dependency list of useEffect
has some unwanted side-effects, for example if notifications
structuruly will stay the same (same items, same length), but will be a new array, useEffect
will miss a cache, since it only does a shallow comparison. Consider using a hashing function of some kind instead of the array itself (e.g. JSON.stringify
)
Related videos on Youtube
RhinoBomb
Updated on April 08, 2020Comments
-
RhinoBomb about 4 years
useState()
is giving me undefined to the new state variable (notifications):const Notifications = (props) => { const [notifications, setNotifications] = useState(props.notifications);//notifications = undefined, props = {notifications: Array(0)} useEffect(() => { if (props.notifications) { setNotifications(props.notifications); } }, [props.notifications]); // do stuff....
I am expecting notifications to be
[]
and then subsequently update it withsetNotifications()
whenprops.notifications
changes.props.notification
is coming from a redux store. I don't know if this changes anything but i did set an initial State.const initialState = Immutable.fromJS({ notifications: [], });
Don't know why i am getting undefined...
Edit: Got rid of typo and testing code
-
iambinodstha about 5 yearsif you want to set initialState an empty array then initialize empty array in
useState([])
-
RhinoBomb about 5 years@binodstha7 I tried using
useState([])
butnotifications
become undefined inside theuseEffect()
. -
Andy Ray about 5 yearsIf you're seeing the
notifications
variable getting set toundefined
, then you're passing itundefined
for the initial value touseState
. Is your component rendering once with notifications and then again without? You're making an assumption that some code we can't see is working, and it isn't. -
iambinodstha about 5 yearscheck what is comming in
props.notification
byconsole.log(props.notification)
inuseEffect
method if props.notification consoled undefined than you have problem in redux part. -
Dominic about 5 yearsthe state will get set once so make sure props.notifications is not undefined initially
-
Aprillion about 5 yearslooks like a typo to me:
notification
withouts
somewhere?
-
-
Victor Zamanian over 4 yearsInstead of using a hashing function, I suggest creating new arrays. New state? Entirely new objects for the changed values.