I'm learning react with redux and I want to achieve something like this:
When I go to this url:
some_url/posts/1
I want to fetch from my server some data and then show it on page.
However it throws null pointer exception because it takes some time to get data.
I did something like this but it doesnt looks well, what is the proper way to prevent this null pointer exception and wait untill data will arrive?
Inside my component:
componentWillMount() {
this.props.fetchPost(
parseInt(this.props.match.params.postId));
}
render(){
return(
<div>
{post.title}
</div>
)};
My action creator:
export function fetchPost(postId){
const request = axios.get(`${ROOT_URL}/posts${postId}`);
return {
type: FETCH_POST,
payload: request
};
}
And reducer, here I just filled state with empty template of object which server is providing. Without this I got NullPointerException.
import { FETCH_POST } from "../actions";
export default function(state = {id: 0, title: "", infos: [{id: 0, content: "", authorId: 0}]}, action){
switch(action.type){
case FETCH_POST:
return action.payload;
}
return state;
}
What is the proper way to wait until data will arrive?