user10408806
user10408806

Reputation:

Easy Peasy state managment - How to fetch and pass data correctly?

I am using Easy Peasy State management for React. I would like to create multiple Axios call from one store location and import it in each page there where I need to show the correct data. I am trying to fetch a JSON placeholder data for example and use that inside a component to push it to the state using Hooks.

But I get the following error:

model.js:14 Uncaught (in promise) TypeError: actions.setTodos is not a function
    at model.js:14

Can someone help me out? What am I doing wrong?

My code for the store (model.js):

import { thunk } from 'easy-peasy';

export default {
    todos: [],
    fetchTodos: thunk(async actions => {
        const res = await fetch(
            'https://jsonplaceholder.typicode.com/todos?_limit=10'
        );
        const todos = res.json();

        actions.setTodos(todos);
    }),
};

My Page component Contact:

import React, { useState, useEffect } from 'react';

import { useStoreActions } from 'easy-peasy';

import ReactHtmlParser from 'react-html-parser';

import { API_URL } from 'constants/import';

// import axios from 'axios';

const Contact = () => {
    const [contactPage, setContactPage] = useState([]);

    const { page_title, page_content, page_featured_image } = contactPage;

    const fetchTodos = useStoreActions(actions => actions.fetchTodos);

    useEffect(() => {
        fetchTodos();
    }, []);

    return (
        <section className="contact">
            <div className="page">
                <div className="row">
                    <div className="col-xs-12">
                        <h3 className="section__title">{page_title}</h3>
                        {ReactHtmlParser(page_content)}
                        {page_featured_image && (
                            <img src={API_URL + page_featured_image.path} />
                        )}
                    </div>
                </div>
            </div>
        </section>
    );
};

export default Contact;

Upvotes: 2

Views: 1085

Answers (1)

Diego Castanho
Diego Castanho

Reputation: 301

You need to use action.

import { action, thunk } from "easy-peasy";

export default {
    fetchTodos: thunk(async (actions, payload) => {
        const res = await fetch(
            "https://jsonplaceholder.typicode.com/todos?_limit=10"
        );
        const todos = res.json();

        actions.setTodos(todos);
    }),

    
    todos: [],
    setTodos: action((state, payload) => {
        console.log("---->>> payload!")
        state.todos = payload
    }),

};

I usually use it like this, it works perfectly for me.

Upvotes: 1

Related Questions