I want to create a context that is actually ing from some async service (server data for example)..
//the async service to bring the context data
export const fetchContextFromAsycnService = () => {
return new Promise(resolve => setTimeout(
() => resolve('Hey, im in the async context and I am the correct value'), 200)
);
}
class App extends Component {
render() {
let value = 'Im not the correct value';
fetchContextFromAsycnService().then(x => value = x as string);
return (
<AsyncContext.Provider value={value}>
<SomeComponent />
</AsyncContext.Provider>
);
}
}
//user the value
export const SomeComponent = ( ) => {
return (
<AsyncContext.Consumer>
{value => <div>{value}</div>}
</AsyncContext.Consumer>)
}
render(<App />, document.getElementById('root'));
.tsx
The expected value is: Hey, I'm in the async context and I am the correct value
, but for some reason im not getting the data after it was fetched.
is there a way to create a context with
I want to create a context that is actually ing from some async service (server data for example)..
//the async service to bring the context data
export const fetchContextFromAsycnService = () => {
return new Promise(resolve => setTimeout(
() => resolve('Hey, im in the async context and I am the correct value'), 200)
);
}
class App extends Component {
render() {
let value = 'Im not the correct value';
fetchContextFromAsycnService().then(x => value = x as string);
return (
<AsyncContext.Provider value={value}>
<SomeComponent />
</AsyncContext.Provider>
);
}
}
//user the value
export const SomeComponent = ( ) => {
return (
<AsyncContext.Consumer>
{value => <div>{value}</div>}
</AsyncContext.Consumer>)
}
render(<App />, document.getElementById('root'));
https://stackblitz./edit/react-ts-8zzbxa?file=index.tsx
The expected value is: Hey, I'm in the async context and I am the correct value
, but for some reason im not getting the data after it was fetched.
is there a way to create a context with
1 Answer
Reset to default 5but for some reason im not getting the data after it was fetched.
value
is not part of the state and does not cause a re-render. Thus, you haven't seen the updated value being displayed after fetch.
To make this work, just make value
part of the state to cause a re-render.
state = {
value: 'Im not the correct value'
}
ponentDidMount() {
// move side-effects in here
fetchContextFromAsycnService().then(value => this.setState({ value }));
}
render() {
return (
<AsyncContext.Provider value={this.state.value}>
<SomeComponent />
</AsyncContext.Provider>
);
}
See Demo
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744168913a4561437.html
评论列表(0条)