score:1
You can't escape it, you must check nullability somewhere:
- Within every consumer (
useContext
) user, the easiest way is to write a custom hook and check for nullability there. - Or, within the provider itself, conditionally render children
Notice that it isn't a "first render" problem since its a promise, you can delay it for enough time that it will update after the first render.
export default function App() {
const [myObj, setMyObj] = useState();
useEffect(() => {
Promise.resolve({ id: 42, text: 'some value from promise' }).then((res) => {
setTimeout(() => {
setMyObj(res);
}, 2000);
});
}, []);
const children = useMemo(
() => (
<div>
<h1>Hello StackBlitz!</h1>
<AnotherPage />
</div>
),
[]
);
return (
<MyContext.Provider value={myObj}>{myObj && children}</MyContext.Provider>
);
}
score:0
You can initialize the Context with some temporary value instead of null.
Instead of Doing
const MyContext = createContext(null);
Do
const MyContext = createContext({id: -1, text: 'yet to be initialized'});
So you child component will consume this values until the promise updates the context value.
score:0
I would solve it like this:
const ASYNC_STATUS = {
Idle: 'idle',
Pending: 'pending',
Success: 'success',
Failed: 'failed',
};
export default function App() {
console.log('App');
const [myObj, setMyObj] = useState({
value: null,
status: ASYNC_STATUS.Idle,
});
useEffect(() => {
try {
setMyObj((prev) => ({
...prev,
status: ASYNC_STATUS.Pending,
}));
Promise.resolve({ id: 42, text: 'some value from promise' }).then(
(res) => {
console.log('resolved: ', res);
setMyObj({
value: res,
status: ASYNC_STATUS.Success,
});
}
);
} catch {
setMyObj((prev) => ({
...prev,
status: ASYNC_STATUS.Success,
}));
}
}, []);
return (
<MyContext.Provider value={myObj}>
<div>
<h1>Hello StackBlitz!</h1>
<AnotherPage />
</div>
</MyContext.Provider>
);
}
const AnotherPage = () => {
console.log('AnotherPage');
const { value, status } = useContext(MyContext);
console.log('myObj', value);
return (
<div>
{status === ASYNC_STATUS.Pending && <div>Loading...</div>}
{status === ASYNC_STATUS.Failed && <div>Failed!</div>}
{status === ASYNC_STATUS.Success && value && <div>here what you want to show</div>}
</div>
);
};
score:1
I think you can use a loader until the promise resolves. Such that the child components doesn't even get rendered before the promise resolves.
import React from 'react';
import { createContext, useEffect, useState, useContext } from 'react';
import './style.css';
const MyContext = createContext(null);
export default function App() {
console.log('App');
const [myObj, setMyObj] = useState();
useEffect(() => {
Promise.resolve({ id: 42, text: 'some value from promise' }).then((res) => {
console.log('resolved: ', res);
setMyObj(res);
});
}, []);
return (
<MyContext.Provider value={myObj}>
{
myObj ? <div>
<h1>Hello StackBlitz!</h1>
<AnotherPage />
</div> : <div>Loading....</div>
}
</MyContext.Provider>
);
}
const AnotherPage = () => {
console.log('AnotherPage');
const obj = useContext(MyContext);
console.log('myObj', obj);// undefined/null at first page render...
return <div>Hello from another page</div>;
};
Source: stackoverflow.com
Related Query
- Issue with async value for React context not available from child component
- React context value not available in child class component
- Why is child component not receiving updated value from parent in React Native?
- React child component not rendering props from parent value
- How to pass input values from a child Form component to the state of its parent component for submission with react hooks?
- Value not getting passed from child to parent component in React
- value is not passed to child component using context in react
- objects are not valid as a react child (found object with keys) while passing props from one component to other
- Passing a function with React Context API to child component nested deep in the tree to update state value
- Get value and not [object Promise] from async function in React Component
- How to change a value from parent component in a child component with useState React hook
- Pass value from parent to child component with React
- How to update state in child component with context value from parent (class components)
- React Context API not working from custom NPM component library
- Passing a function with React Context API to child component nested deep in the tree
- Updating Parent Component State from Child Component with UseState React Hook
- React warns about passed prop with value null, where the PropType for the prop is not required
- Issue with async default value in React Material UI Autocomplete
- React JS this.props.data not defined in getInitialState for child component even though it is defined in render (and is defined in parent)
- How to pass input value from child to parent component react
- How to communicate from Child Component to Parent Component with React Router
- Add value to React context from child components
- How is an argument for a callback in React being passed from the child component to the parent component?
- Watching state from child component React with Material UI
- Wait for change of prop from parent component after changing it from a child in React
- pass async results from parent to child component react functional component
- React Context not updating for class as value
- Refresh a React Child Functional Component based on Async input from Parent
- page title not available with jest/enzyme for testing react app, how to get the title?
- lodash , convert string from svg circle (properties and values separates with space) to object for spread in react component inline
More Query from same tag
- how to map in jsx a json string that has image and text information
- React - stateless component, function inside or outside component
- How to align 2 rows horizontally in react?
- Material UI - Switch Button the individual data according to status
- Struggling to update list in object array
- react-materialize $(...).tabs is not a function
- Why we shouldn't modify the state directly in ReactJS?
- How to fix babel react "Uncaught SyntaxError: Unexpected token <"
- Props object what is the meaning of passing children to the component from React official documentation
- Gatsby node fails to generate page
- React Router render vs component giving me error
- How to prevent a local state reset while dispatching action to reducer?
- how to create React search filter for search multiple object key values
- Sending PUT data using Fetch API in React.js
- Display a button in X axis with recharts
- Button disabled attribute is not updated correctly when two renders of the same component are performed
- react router and passport.js
- Error while deleting S3 objects - likely an issue with credentials but could not locate the problem
- React es6, Remove item from array, by changing props
- How to solve TypeError: environment.teardown is not a function
- React JS - Fetch data display in React JS Form
- Removing one object from an array by its id, react.js
- The search icon won't appear when using MDBIcon
- Error dynamically adding table rows in reactJs
- React - move row of data to new table based on checkbox
- How to set previous State as default values in react material-ui select
- Polygon mask SVG image not working for tsparticles in React
- React Bootstrap Cards and CardDeck Components - responsive layout
- Removing object element from array of object in state (React.js)
- How to implement a custom cursor component in react