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
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.
Related
I have a basic job board application. An API is called within the redux store (using thunk function) and initial job results are then saved in redux store.
Ref: https://redux.js.org/tutorials/essentials/part-5-async-logic
These initial Jobs are stored in redux store (and not in local component state), as I need to access these initial job results in other components as well
There are also three filters that can be applied to these initial jobs (Jobs can be filtered by location, team and commitment) I've put these filters inside the redux store as well. (Actions are triggered from
Filter UI component to update the current applied filters, and multiple filters can be active at one time)
The Filter UI component pretty much just renders a <Select> element with a handleChange function which causes the filters to update in the redux store, something like this:
Basic Filter UI Component which dispatches action :
<Select
name={name}
value={value}
onChange={handleChange}
></Select>
// ... omit some code ...
const handleChange = (event) => {
const { name } = event.target;
switch (name) {
case 'location':
dispatch(changeLocationFilter(event.target))
break;
case 'team':
dispatch(changeTeamFilter(event.target))
break;
case 'commitment':
dispatch(changeCommitmentFilter(event.target))
break;
}
}
Here is my filtersSlice in redux, which update the redux state when filters are applied:
import { createSlice } from "#reduxjs/toolkit";
import { ALL_LOCATIONS, ALL_TEAMS, ALL_COMMITMENTS } from '../constants'
const initialState = {
location: ALL_LOCATIONS,
team: ALL_TEAMS,
commitment: ALL_COMMITMENTS
};
export const filtersSlice = createSlice({
name: "filters",
initialState,
reducers: {
changeLocationFilter: (state, action) => {
const { payload: { value: locationValue } } = action;
state.location = locationValue;
},
changeTeamFilter: (state, action) => {
const { payload: { value: teamValue } } = action;
state.team = teamValue;
},
changeCommitmentFilter: (state, action) => {
const { payload: { value: commitmentValue } } = action;
state.commitment = commitmentValue;
}
}
});
// Action creators are generated for each case reducer function
export const { changeLocationFilter, changeTeamFilter, changeCommitmentFilter } = filtersSlice.actions;
export default filtersSlice.reducer;
Every time those filters change, I'm using a memoized createSelector function to get those updated filters, then I'm filtering my jobs locally within my JobContainer component
Ref:
https://redux.js.org/tutorials/essentials/part-6-performance-normalization
Ref:
https://redux-toolkit.js.org/api/createSelector
I am not updating the jobs in the redux store (From initial jobs to filtered jobs) because after doing some reading, it seems that when it comes to filtering data, the generally accepted best practice is to do this via derived state, and there is no need to put this inside component state or redux store state -
Ref:
What is the best way to filter data in React?
Here is some code to illustrate my example further:
Here is my JobsContainer component, which get the initial jobs and the filters from the redux store, and then filters the jobs locally:
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { createSelector } from "reselect";
import Job from "../../components/Job";
import { ALL_LOCATIONS, ALL_TEAMS, ALL_COMMITMENTS } from '../../constants'
import { fetchReduxJobs, selectAllReduxJobs } from '../../redux/reduxJobs'
const JobsContainer = () => {
const dispatch = useDispatch()
const reduxJobsStatus = useSelector(state => state.reduxJobs.status);
let reduxJobs = useSelector(selectAllReduxJobs); // GET INITIAL JOBS FROM REDUX STATE HERE
const filterState = useSelector((state) => state.filters); // GET FILTERS FROM REDUX STATE HERE
const selectLocation = filterState => filterState.location
const selectTeam = filterState => filterState.team
const selectCommitment = filterState => filterState.commitment
// CREATE MEMOIZED FUNCTION USING CREATESELECTOR, AND RUN A FILTER ON THE JOBS
// WHENEVER FILTERS CHANGE IN REDUX STORE
const selectFilters = createSelector([selectLocation, selectTeam, selectCommitment], (location, team, commitment) => {
let tempReduxJobs = reduxJobs;
tempReduxJobs = tempReduxJobs.filter((filteredJob) => {
return (
(location === ALL_LOCATIONS ? filteredJob : filteredJob.categories.location === location) &&
(commitment === ALL_COMMITMENTS ? filteredJob : filteredJob.categories.commitment === commitment) &&
(team === ALL_TEAMS ? filteredJob : filteredJob.categories.team === team)
)
})
return tempReduxJobs;
})
reduxJobs = selectFilters(filterState); // UPDATE JOBS HERE WHEN FILTERS CHANGE
let content;
if (reduxJobsStatus === 'loading') {
content = "Loading..."
} else if (reduxJobsStatus === 'succeeded') {
// JUST MODIFYING MY JOBS A BIT HERE BEFORE RENDERING THEM
let groupedReduxJobs = reduxJobs.reduce(function (groupedObj, job) {
const { categories: { team } } = job;
if (!groupedObj[team]) {
groupedObj[team] = []
}
groupedObj[team].push(job)
return groupedObj
}, {})
// THIS IS HOW I RENDER MY JOBS HERE AFTER MODIFYING THEM
content = Object.keys(groupedReduxJobs).map((teamName, index) => (
<div key={index}>
<div className="job-team-heading">{teamName}</div>
{groupedReduxJobs[teamName].map((job) =>
(<Job jobDetails={job} key={job.id} />))
}
</div>
))
// return groupedObj
} else if (reduxJobsStatus === 'failed') {
content = <div>{error}</div>
}
useEffect(() => {
if (reduxJobsStatus === 'idle') {
dispatch(fetchReduxJobs())
}
}, [reduxJobsStatus, dispatch])
return (
<JobsContainerStyles>
<div>{content}</div>
</JobsContainerStyles>
);
}
export default JobsContainer;
Something about how Im updating my jobs after the filters change (inside JobsContainer) using my selectFilters function ie the line:
reduxJobs = selectFilters(filterState);
Seems off. (Note: as you can see, I am modifying the data a bit before rendering as well - see groupedReduxJobs)
I wouldn't be as confused if I was to update the redux store with the filtered jobs after the filter is applied, but as I mentioned, reading into this topic suggests filtered data should generally be kept as derived state, and not in redux store. This is what I am confused about.
Can someone provide some constructive criticism on how I'm doing this please ? Or is the way Im doing this currently a good way to go about solving this problem.
To clarify, this is all working as written here .. but I'm not sure what other's opinions are on doing it this way vs some other way
Standard JS file:
// functions.js
import cockpit from "cockpit";
import { store } from "state-pool";
const global_status = {
key1: null,
key2: null,
}
store.setState("status", global_status);
function update_config(data, message) {
const json_data = JSON.parse(data);
store.setState("status", {
key1: json_data.key1,
key2: json_data.key2,
};)
}
export function get_config() {
cockpit.spawn(python_script, superuser: "try", err: "message" })
.done(function (data, message) { update_config(data, message) })
.fail(function (error) { console.log(["spawn() failed: ", error]) });
}
// Initial loading of values
get_config()
In my JSX file I have this:
// app.jsx
import React, { useEffect } from 'react';
import { Alert, Card, CardTitle, CardBody } from '#patternfly/react-core';
import { store, useGlobalState } from 'state-pool';
function ShowStatus () {
const stat = store.getState("status");
const info = stat.key1 ? "info" : !stat.key1 ? stat.installed ? "error" : "warning";
const status = stat.key2 ? "Enabled" : !stat.key2 ? "Available" : "Unkown";
return (
<Alert variant={info} title={status} />
);
}
export function App () {
const [status] = useGlobalState('status');
useEffect(
() => ShowStatus, [status]
);
return (
<Card>
<CardTitle>Status</CardTitle>
<CardBody>
<ShowStatus />
</CardBody>
</Card>
);
}
When rendering this in Fedora Cockpit, it works, but only the initial loading of values (key1: null, key2: null) show. After get_config() is called, the status page never updates.
I've used console.log() and verified that "status" gets updated after get_config() is called, but the page does not render with the newer data.
CAVEAT: It's been some time since I coded in JS, and this is the first time I'm using React.
I've read the React docs as well as about 30 answers from stackoverflow about this, but I still have some issues getting around some of the Reactisms.
Any help would be greatly appreciated.
update:
One of the variations I've tried:
// app.jsx
function ShowStatus (stat) {
const info = stat.key1 ? "info" : !stat.key1 ? stat.installed ?
...
}
export function App () {
...
<CardBody>
<ShowStatus stat={status} />
</CardBody>
...
Reason for putting get_config() in a separate file is due to several different pages may end up trying to update the configuration setup.
I had similar issue... trying to recreate what you've done here, I believe you have to "subscribe" to the keys you want to have update your render function.
From the github readme:
store.subscribe & globalState.subscribe
If you want to listen to changes in a store you can subscribe to it by using
store.subscribe. it accepts an observer function. For example
// Subscribe to store changes
const unsubscribe = store.subscribe(function(key: String, value: Any){
// key is the key for a global state that has changed
// value is the new value of a global state
})
// You can unsubscribe by calling the result
unsubscribe();
Here is how it is accomplished in the test file:
import React from 'react';
import { renderHook, act } from '#testing-library/react-hooks';
import { createStore } from '../src/';
const store = createStore();
store.setState("count", 0);
let testVal1 = 0;
let testVal2 = 0;
test('should update testVal1 & testVal2 through subscribers', () => {
const { result } = renderHook(() => store.useState("count"))
act(() => {
store.subscribe((key, value) => {
testVal1 = 1
})
store.getState("count").subscribe((value) => {
testVal2 = 2
})
result.current[2](count => 1)
})
expect(testVal1).toStrictEqual(1);
expect(testVal2).toStrictEqual(2);
})
in my EventForm i have this const, this is a dialog form
this is my EventForm.js
const EventForm = (props) => {
const { setOpenPopup, records, setRecords, setMessage, setOpenSnackbar } = props
const addEvent = () => {
axios.post('https://jsonplaceholder.typicode.com/events', (event)
.then(resp => {
console.log(resp.data)
const newData = [{
title: resp.data.name,
start: resp.data.starts_at,
end: resp.data.ends_at
}]
setRecords([{ ...records, newData}])
//
setOpenPopup(false)
setMessage('New Event added')
setOpenSnackbar(true)
})
.catch([])
}
export default EventForm
EventForm.propTypes = {
setOpenPopup: PropTypes.func,
records: PropTypes.array,
setRecords: PropTypes.func,
setMessage: PropTypes.func,
setOpenSnackbar: PropTypes.func
}
}
in my EventTable.js
const [records, setRecords] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/events')
.then(resp => {
const newData = resp.data.map((item) => ({
title: item.name,
start: item.starts_at,
end: item.ends_at
}))
setRecords(newData)
})
.catch(resp => console.log(resp))
}, [])
fullcalendar...
events={records}
im trying to push the API post response to my setRecords. so when the dialog form close it will not use the GET response. ill just get the new record and render to my view
but im getting an error:
Unhanded Rejection (TypeError): setRecords is not a function
I suspect you are using React Hooks. Make sure that your records state looks like this
const [records, setRecords] = useState([]);
In your axios request, it looks like that you are trying to spread the values of records which is an array to an object. I'd suggest refactoring this to something like this. Instead of trying to spread an array into the object, take the previous state and merge it with the new one.
setRecords(prevRecords => [...prevRecords, ...newData])
Here's an example using React Hooks how the component could look like
import React from "react";
import axios from "axios";
const MyComponent = ({
setOpenPopup,
records,
setRecords,
setMessage,
setOpenSnackbar
}) => {
const addEvent = () => {
axios
.post("https://jsonplaceholder.typicode.com/events", event) // Make sure this is defined somewhere
.then((resp) => {
const { name, starts_at, ends_at } = resp.data;
const newData = [
{
title: name,
start: starts_at,
end: ends_at
}
];
setRecords((prevRecords) => [...prevRecords, ...newData]);
setOpenPopup(false);
setMessage("New Event added");
setOpenSnackbar(true);
})
.catch([]);
};
return (
<div>
<button onClick={addEvent}>Click me </button>
</div>
);
};
export default MyComponent;
If you are not using React Hooks and use Class components, then make sure that you pass setRecords to your component in props. Plus, in your props destructuring, make sure you add this to the props, otherwise, it can lead to unwanted behaviour. Also, move your request function out of the render method and destructure values from the props that you need inside the function. I've also noticed that your axios syntax was incorrect (forgot to close after the event) so I fixed that as well. Here's an example of how you can improve it.
import React from "react";
import axios from "axios";
class MyComponent extends React.Component {
addEvent = () => {
const {
setOpenPopup,
setRecords,
setMessage,
setOpenSnackbar
} = this.props;
axios
.post("https://jsonplaceholder.typicode.com/events", event)
.then((resp) => {
console.log(resp.data);
const newData = [
{
title: resp.data.name,
start: resp.data.starts_at,
end: resp.data.ends_at
}
];
setRecords((prevRecords) => [...prevRecords, ...newData]);
//
setOpenPopup(false);
setMessage("New Event added");
setOpenSnackbar(true);
})
.catch([]);
};
render() {
return (
<div>
<button onClick={() => this.addEvent()}>Click me</button>
</div>
);
}
}
export default MyComponent;
I am new to React Context.
I need to call the API in react context to use its data throughout my react application. Also the same API needs to be called on some CRUD operation on various component of react application.
For now I am storing API data in redux which I don't want to store.
Here is what I have tried..
context.js File
import React, { useState, createContext,useEffect } from 'react';
import {getData} from './actionMethods';
const NewContext = createContext();
function newContextProvider(props) {
useEffect(async () => {
const {dataValue} = await getData()
console.log("Data " , dataValue)
}, [])
return (
<NewContext.Provider
value={{
state: {
},
actions: {
}
}}
>
{props.children}
</NewContext.Provider>
);
}
const newContextConsumer = newContext.Consumer;
export { newContextProvider, newContextConsumer, newGridContext };
actionMethods.js
export function getData() {
let config = getInstance('GET', `${prefix}/xyz/list`)
return axios(config).then(res => res.data).catch(err => {
console.log(err)
})
}
when any CRUD operation performs , I need to call the API from the context.js file to get the data from API and store in the context.
Any help would be great.
Thank You.
First we create the Context and pass it an initial value.
In order to fetch data and keep track of the returned value, we create a state inside the component. This component will manage the fetched data and pass it in the Context Provider.
To call an async function inside useEffect we need to wrap it and call it inside useEffect callback.
export const NewContext = createContext({
my_data: {} // Initial value
});
export const NewContextProvider = props => {
const [my_data, setMyData] = useState({});
useEffect(() => {
const fetchMyData = async () => {
const { dataValue } = await getData();
if (dataValue) {
setMyData(dataValue);
} else {
// There was an error fetching the data
}
};
fetchMyData();
}, []);
return (
<NewContext.Provider
value={{
my_data
}}
>
{props.children}
</NewContext.Provider>
);
};
To use this Context in a component we use the useContext hook. Remember that this component needs to be wrapped by the Provider we just created.
import React, { useContext } from "react";
import { NewContext } from "./NewContext"; // The file where the Context was created
export const MyComponent = props => {
const { my_data } = useContext(NewContext);
return //...
};
Let me know if something is not clear.
I have created a Network service component which deals with the API call. I want to retrieve state from other components which update the store.
Im having trouble getting the state so I started using Redux, but I havent used Redux before and still trying to find a way to pass the state to the NetworkService. Any help would be great, thanks!
Here is my NetworkService.js
import RequestService from './RequestService';
import store from '../store';
const BASE_URL = 'api.example.com/';
const REGION_ID = //Trying to find a way to get the state here
// My attempt to get the state, but this unsubscribes and
// doesnt return the value as it is async
let Updated = store.subscribe(() => {
let REGION_ID = store.getState().regionId;
})
class NetworkService {
getForecast48Regional(){
let url =`${BASE_URL}/${REGION_ID }`;
return RequestService.getRequest(url)
}
}
export default new NetworkService();
store.js
import {createStore} from 'redux';
const initialState = {
regionId: 0
};
const reducer = (state = initialState, action) => {
if(action.type === "REGIONAL_ID") {
return {
regionId: action.regionId
};
}
return state;
}
const store = createStore(reducer);
export default store;
My folder heirarchy looks like this:
-App
----Components
----NetworkService
----Store
Do not import store directly. Use thunks/sagas/whatever for these reasons.
NetworkService should not know about anything below.
Thunks know only about NetworkService and plain redux actions.
Components know only about thunks and store (not store itself, but Redux's selectors, mapStateToProps, mapDispatchToProps).
Store knows about plain redux actions only.
Knows - e.g. import's.
//////////// NetworkService.js
const networkCall = (...args) => fetch(...) // say, returns promise
//////////// thunks/core/whatever.js
import { networkCall } from 'NetworkService'
const thunk = (...args) => (dispatch, getState) => {
dispatch(startFetch(...args))
const componentData = args
// I'd suggest using selectors here to pick only required data from store's state
// instead of passing WHOLE state to network layer, since it's a leaking abstraction
const storeData = getState()
networkCall(componentData, storeData)
.then(resp => dispatch(fetchOk(resp)))
.catch(err => dispatch(fetchFail(err)))
}
//////////// Component.js
import { thunk } from 'thunks/core/whatever'
const mapDispatchToProps = {
doSomeFetch: thunk,
}
const Component = ({ doSomeFetch }) =>
<button onClick={doSomeFetch}>Do some fetch</button>
// store.subscribe via `connect` from `react-redux`
const ConnectedComponent = connect(..., mapDispatchToProps)(Component)