I have the following epic in redux-observable
export const landingEpic = action$ => (
action$.ofType('LOAD_USERS').delay(5000).map(() => ({
type: 'USERS_LOADED',
UserList: ['a','b','c','d']
}))
);
So far I am fine, however I want the epic to dispatch a 'LOADING_USERS' action so that I can display a processing message, while the users are being loaded. Is the epic the right place to do this, and if so how do I do this. If the epic is not the place to do this then where do I do this?
What I want to do is to immediately emit USERS loading and then after 5 seconds emit USERS_LOADED
There are many ways of doing this, here are two:
export const landingEpic = action$ =>
action$.ofType('LOAD_USERS')
.mergeMap(() =>
Observable.of({
type: 'USERS_LOADED',
UserList: ['a','b','c','d']
})
.delay(5000)
.startWith({
type: 'LOADING_USERS
})
);
export const landingEpic = action$ => (
action$.ofType('LOAD_USERS')
.mergeMap(() =>
Observable.timer(5000)
.map(() => ({
type: 'USERS_LOADED',
UserList: ['a','b','c','d']
}))
.startWith({
type: 'LOADING_USERS
})
);
The key here is that we need to use mergeMap (or switchMap, etc depending on your use case) to isolate our top-level chain so that we can create an Observable that produces two actions at different times. startWith is also handy, but could also use concat for the same effect:
Observable.concat(
Observable.of({ type: 'LOADING_USERS }),
Observable.of({
type: 'USERS_LOADED',
UserList: ['a','b','c','d']
})
.delay(5000)
)
I think you can do something like the following:
const landingEpic = action$ => (
action$.ofType('LOAD_USERS').delay(5000).flatMap(() => (Observable.concat(
{
type: 'USERS_LOADING'
},
{
type: 'USERS_LOADED',
UserList: ['a','b','c','d']
}))));
Related
I have the following code:
const contractStorage = new MMKVLoader().initialize()
export const useStore = create<StoreType>()(
persist(
(set) => ({
contracts: {},
setContracts: (contract: Contract) => set((state) => ({ ...state, [contract.id]: contract })),
}),
{
name: 'contract-storage',
version: 0,
getStorage: () => contractStorage,
},
),
)
This accesses the methods defined on the MMKVLoader, one of which being setItem, which updates the entire instance
Is there a way to use the persist middleware to only update the specific key/value pair in the storage that has actually changed?
My current workaround is the following:
export const useStore = create<StoreType>()(
(set) => ({
contracts: {},
setContracts: (contract: Contract) => set((state) => {
contractStorage.setMap(contract.id, contract)
return ({ ...state, [contract.id]: contract })
}),
})
)
I have a bit of code that is trying to fetch some data and save it to update a list array but is is not updating it. The code below is some hard coded array that works fine but in the second I try to fetch the data but nothing?
Any idea where I am going wrong, I am not really getting the hang of this. Thanks
The code which works :-
const data = [
{id: '1', name: 'A'},
{id: '2', name: 'B'},
{id: '3', name: 'C'},
{id: '4', name: 'D'},
{id: '5', name: 'E'}
];
export default function App() {
const [lists, setLists] = useState(data);
And what I am trying to use to fetch :
export default function App() {
const fetchURL = 'https://www.uberfantasies.com/rn.php'
const [lists, setLists] = useState('');
const getData = () =>
fetch(fetchURL)
.then((res) => res.json());
useEffect(() => {
getData().then((lists) => setLists(res.data) // If I use data it can display the hard coded array //
}, []);
What am I doing wrong?
This will load the data once and update the list when the component mounts
const [lists, setLists] = useState('')
useEffect(() => {
const fetchURL = 'https://www.uberfantasies.com/rn.php'
fetch(fetchURL)
.then((res) => res.json())
.then((json) => setLists(json?.data))
.catch(console.warn)
}, [])
Can you log the response of your getData function instead of setting it to state? Also can you refactor your function to something like this pls.
Also, in the useEffect function, where did that res variable come from? I assume it should be lists.
const getData = async () => {
const res = await fetch(fetchURL);
console.log(res);
const json = await res.json();
console.log(json);
return json;
};
useEffect(() => {
getData().then((lists) => console.log(lists));
}, [])
I am trying to get a json response from an api and get the data successfully but when I call a action within another action using redux-thunk, my data is not available inside the reducer. I need data in "data" property inside my reducer get in component. Check the code below.
This is my action
import { GET_REPORT, GET_DATA_SUCCESS } from './types';
export const getData = (text) => {
return (dispatch) => {
dispatch ({ type: GET_REPORT})
fetch('http://api.openweathermap.org/data/2.5/forecast?q='+text+'&cnt=1&units=metric&APPID={key}')
.then(response => response.json())
.then(data => getDataSuccess(dispatch, data.list[0]))
.catch((error) => console.log(error));
};
};
const getDataSuccess = (dispatch, data) => {
//console.log(data);
dispatch({
type: GET_DATA_SUCCESS,
payload: data
});
}
this is my reducer
import { GET_REPORT } from'../actions/types';
const INITIAL_STATE = {
data: '',
}
export default (state = INITIAL_STATE, action) => {
switch(action.type){
case GET_REPORT:
console.log(action.payload); // getting undefined
return {...state, data: action.payload};
default:
return state;
}
}
I need data in "data" property get in component.
you are missing GET_DATA_SUCCESS in your reducer
The action dispatch ({ type: GET_REPORT}) , doesn't contain a payload hence undefined. Either you need to make reducer to handle action GET_DATA_SUCCESS or modify the existing one.
To simplify, dispatch({
type: GET_DATA_SUCCESS,
payload: data
}); contains a payload whereas dispatch ({ type: GET_REPORT}) doesn't
Resolved it by adding new switch case for GET_DATA_SUCCESS and get the payload from getDataSuccess and removing the payload from GET_REPORT case.
Now switch case looks like this
switch(action.type){
case GET_REPORT:
return {...state};
case GET_DATA_SUCCESS:
console.log(action.payload);
return{...state, data: action.payload}
default:
return state;
}
I have two async requests, want to write a epic do the job like promise.all()
const fetchData1 = () => (action$: ActionsObservable<any>, store: any) => (
ajax.getJSON('../../mockData/promiseAll/data1.json').map((data: any) => {
return requestData1Success(data);
})
);
const fetchData2 = () => (action$: ActionsObservable<any>, store: any) => (
ajax.getJSON('../../mockData/promiseAll/data2.json').map((data: any) => {
return requestData2Success(data);
})
)
const requestAllDataEpic = (action$: ActionsObservable<any>, store: any) => {
return action$.ofType(t.REQUEST_ALL_DATA)
.map((action) => action.payload)
.switchMap((names: string[]) => {
console.log(names);
return Observable.forkJoin([
fetchData1()(action$, store),
fetchData2()(action$, store)
])
.map((results: any[]) => {
const [action1, action2] = results;
requestData1Success(action1);
requestData2Success(action2);
});
});
};
But when I dispatch the action, the console give me an error:
Uncaught TypeError: Cannot read property 'type' of undefined
I think the reason is I do not give the middleware an action object, but undefined.
How can I do this correctly?
In the provided example, you are not actually returning your two actions, you're returning nothing:
.map((results: any[]) => {
const [action1, action2] = results;
// v----- not returning either of these
requestData1Success(action1);
requestData2Success(action2);
});
map can't used to emit two actions sequentially because it's 1:1 not 1:many (mergeMap, switchMap, concatMap, etc are 1:many). However, in your example you are already converting the responses to the actions inside your fetchData helpers--doing it again would wrap an action inside another action, not what you want. This looks like a bug when you were refactoring.
Other than that, it's actually not clear what you intended to do. If you have further questions you'll need to describe what you want you'd like to achieve.
I am writing an epic using redux-observable and am trying to write an epic using multiple filters (oftype). Given below is my sample code
export const landingEpic = action$ => {
console.log('inside landing epic');
return action$.ofType('APPLY_SHOPPING_LISTS').map(() => (
{
type: 'APPLYING_SHOPPING_LISTS',
})
);
return action$.ofType('APPLIED_SHOPPING_LIST'){
//here I want to return something else
}
}
However I cannot have two return methods in one epic?
You'll want to combine them with Observable.merge() then return that--however I also highly suggest separating them into two separate epics. It will make it easier to test, but that's of course your call.
export const landingEpic = action$ => {
return Observable.merge(
action$.ofType('APPLY_SHOPPING_LISTS')
.map(() => ({
type: 'APPLYING_SHOPPING_LISTS',
}),
action$.ofType('APPLIED_SHOPPING_LIST')
.map(() => ({
type: 'SOMETHING_ELSE',
}),
);
}
It sounds like you want to use combineEpics:
import { combineEpics } from "redux-observable";
const landingEpic1 = // put epic1 definition here
const landingEpic2 = // put epic2 definition here
export default combineEpics(
landingEpic1,
landingEpic2,
// ...
);