era s'q
era s'q

Reputation: 591

How to set state of other component inside an axios get method in react?

I'm using class-based components in react. I have few components named as follows: Blogs, BlogsClient, BlogCard. When Blogs mounts I make a call to a function inside BlogClient named as getBlogContent to fetch me data using axios.

setBlogs = (blogs) => {
    this.setState({ "blogs": blogs });
}

componentDidMount() {
    getBlogContent(this.setBlogs);
}

where getBlogContent is:

let getBlogContent = (setBlogs) => {
store.set('loaded', false);
axios.get(ADMIN_URL + '/getAllBlogs')
    .then(response => {
        store.set('loaded', true);
        setBlogs(response.data.Response);
    })
    .catch(error => {
        store.set('loaded', true);
        store.set('errorMessage', error);
    })
}

I'm able to fetch data and update my state properly. But If there comes any error inside Blogs or BlogCard(which is called inside Blogs) it goes inside the catch of getBlogContent whereas it should be only responsible for catching Axios error. What am I missing here?

Upvotes: 0

Views: 31

Answers (1)

k-wasilewski
k-wasilewski

Reputation: 4623

Ok, so it's hard to tell without knowing these errors..

But nonetheless, you should avoid setting the component's state outside that component. So, your code'd become:

componentDidMount() {
    const blogContent = getBlogContent();

    if (blogContent !== 'error'j this.setBlogs(blogContent);
}

let getBlogContent = () => {
store.set('loaded', false);
return axios.get(ADMIN_URL + '/getAllBlogs')
    .then(response => {
        store.set('loaded', true);
        return response.data.Response;
    })
    .catch(error => {
        store.set('loaded', true);
        store.set('errorMessage', error);
        return 'error';
    })
}

Upvotes: 1

Related Questions