6

lets say this is my code

  const donation = useStoreState(
    state => state.user.initialState.donationData,
  )
  const setDonation = useStoreActions(
    actions => actions.donation.setDonation,
  )
  setDonation({
    amount: 1000000,
    message: 'donation from easy peasy',
    payment_method_id: '1',
    receiver_id: '1',
  })
  console.log('donation', donation)

when i tried to console.log it not showing new donation data

Ben Smith
  • 19,589
  • 6
  • 65
  • 93

1 Answers1

4

In easy-peasy initialState is an immutable value used to initialise your store. So your setDonation function wont be able to change this value.

A full (though contrived!) example of what you want to do is shown here, with comments which should explain whats going on:

import React, { Component } from "react";
import { render } from "react-dom";

import {
  useStoreState,
  action,
  createStore,
  StoreProvider,
  useStoreActions
} from "easy-peasy";

// Define your model
const donationModel = {
  donation: {},
  setDonation: action((state, payload) => {
    state.donation = payload;
  })
};

// Define you application store
const storeModel = {
  donations: donationModel
};

// Create an instance of the store
const store = createStore(storeModel);

const App = () => (
  // Wrap the Donation component with the StoreProvider so that it can access the store
  <StoreProvider store={store}>
    <Donation />
  </StoreProvider>
);

const Donation = () => {
  // Dispatch a setDonation action to add donation data to the store
  useStoreActions(actions =>
    actions.donations.setDonation({
      amount: 1000000,
      message: "donation from easy peasy",
      payment_method_id: "1",
      receiver_id: "1"
    })
  );

  // Retrieve data from the store using useStoreState
  const donationMessage = useStoreState(
    state => state.donations.donation.message
  );

  // Display the donation message returned from the store!
  return <>{donationMessage}</>;
};

render(<App />, document.getElementById("root"));

You can find this working here.

Ben Smith
  • 19,589
  • 6
  • 65
  • 93