React Native Flatlist extraData not working redux data changed - reactjs

I have array in redux. I am showing datas on Flatlist. However, When I edited array data , flatlist not re-render. How can i solve this problem? I checked my redux and is working fine
this.props.notes[this.state.Index]={
color: JSON.stringify(BgColor),
date: this.state.fullDate.toString(),
note: this.state.noteText,
name: this.state.noteName,
type: "note",
noteID:this.props.notes[this.state.Index].noteID
}
this.props.editNotes(this.props.notes);
Flatlist code;
<FlatList
ref={(list) => this.myFlatList = list}
data={this.props.notes}
showsVerticalScrollIndicator={false}
renderItem={({item, index})=>(
)}
removeClippedSubviews={true}
extraData={this.props.notes}
/>
mapStateToProps on same page with Flatlist
const mapStateToProps = (state) => {
const { notes } = state
return { notes }
};
Reducer
const notes = [];
const notesReducer = (state = notes, action) => {
switch (action.type) {
case 'editNotes':
return state = action.payload;
default:
return state
}
};
export default notesReducer;

The reason it's not updating is because you're not returning a new array. The reference is same.
Return the updated state like return [...state,action.payload]

The reason it's not updating the data correctly is because the mutation.
The problematic code is this part.
this.props.notes[this.state.Index]={
color: JSON.stringify(BgColor),
date: this.state.fullDate.toString(),
note: this.state.noteText,
name: this.state.noteName,
type: "note",
noteID:this.props.notes[this.state.Index].noteID
}
this.props.editNotes(this.props.notes);
It should be in this way
const { notes, editNotes } = this.props;
const newNotes = [...notes];
const { index } = this.state;
newNotes[index] = {
//update data
}
editNotes(newNotes);

You can fix the issue in many ways but the wrong part I see in your code is Reducer. As per the standard, your reducer should be a Pure Function and the state should not mutate.
const notes = [];
const notesReducer = (state = notes, action) => {
switch (action.type) {
case 'editNotes':
return {
...state,
...action.payload;
},
default:
return state
}
};
export default notesReducer;
This should resolve your issue.
Suggestion:
Try to create a nested hierarchy in redux like
const initialState = {
notes: [],
};
const notesReducer = (state = initialState, action) => {
switch (action.type) {
case 'editNotes':
return {
...state,
notes: [
...state.notes,
...action.payload.notes,
],
},
default:
return state
}
};
export default notesReducer;

Related

react redux thunk not populating state object

im having an issue with my code, its not populating the state object when state action is being performed. im new with redux
i have this code. so far that having an issue
this is the statement that will called the props.action fetchProjectFamilyList
case 'SubBusinessUnit':
setProductFamilyDetailsObj([])
if (selectedOption.id != 0) {
props.actions.fetchDepartment(selectedOption.id)
props.actions.fetchProjectFamilyList(selectedOption.id)
console.log(props)
}
setDropdownDataInState(resetData, 'Department')
setFormFields({
...formFields,
'OtherNamedInsuredIndustry': {
...formFields.OtherNamedInsuredIndustry,
value: ''
},
'NamedInsuredIndustry': {
...formFields.NamedInsuredIndustry,
value: "",
selectedId: 0
},
[fieldName]: {
...formFields[fieldName],
value: selectedOption.description, selectedId: selectedOption.id
}
});
break;
and this is the code for the commonreducer
export const fetchProjectFamilyList = createAsyncThunk(types.FETCH_PROJECT_FAMILY_LIST,
async (option, {getState, rejectWithValue}) => {
const reduxThunkConfig = {
checkStateData:getState().commonReducer.projectFamilyList && getState().commonReducer.projectFamilyList[option],
rejectWithValue
}
const APIConfig = {
URL: "eapi-referencedata/v1/lists/12?filterBySourceList=" + option + "&filterBySourceListValue=15",
method:"getData",
}
console.log('fetchProjectFamilyList')
return fetchCachedData(reduxThunkConfig, APIConfig);
}
)
im using the builder in my case of course inistailstate is set
const initialState = {
projectFamilyList:{},
}
builder.addCase(fetchProjectFamilyList.fulfilled, (state, action) => {
const subDivision = action.meta.arg;
return {
...state,
projectFamilyList:{
...state.projectFamilyList,
[subDivision]: action.payload},
}})
const commonActions = { ...actions, fetchProjectFamilyList }
export { commonActions, commonReducer}
this is the comment that accept the state as props. but the props productFamilyDetailsObj is empty object
<ProductFamilyComponent
productFamilyDetailsObj={productFamilyDetailsObj}
/>
function ProductFamilyComponent({ productFamilyDetailsObj }) {
return <div className="boxLayout">
<p className="smallHeading">Product Families</p>
{productFamilyDetailsObj.map((text, textIndex) => {
let index = textIndex;
return ( .... and so on
I hope theres someone who could help me resolving this. thank in advance.

Problem with Reducer that contains few different values

I'm kind of new to React.js & Redux, so I have encountered a problem with Reducers.
I am creating a site that have a main "Articles" page, "Question & Answers" page, I created for each one a separate Reducer that both work just fine.
The problem is in "Main Page" which contains a lot of small different pieces of information, and I don't want to create each little different piece of information its on Reducer, so I am trying to create one Reducer which will handle a lot of very small different pieces of information, and I can't make that work, inside the main "Content" object, I put 2 Key Value Pairs that each have an array, one for each different information, one is "Features" info, and one for the "Header" info.
This is the error that I'm getting:
Uncaught TypeError: Cannot read property 'headerContent' of undefined
at push../src/reducers/ContentReducer.js.__webpack_exports__.default (ContentReducer.js:15)
I am not sure what's the problem, maybe my code is wrong or maybe my use of the spread operator, any solution?
I have added the necessary pages from my code:
ACTIONS FILE
export const addFeatureAction = (
{
title = 'Default feature title',
feature = 'Default feature',
} = {}) => ({
type: 'ADD_FEATURE',
features: {
id: uuid(),
title,
feature
}
})
export const addHeaderAction = (
{
title = 'Default header title',
head = 'Default header',
} = {}) => ({
type: 'ADD_HEADER',
header: {
id: uuid(),
title,
head
}
})
REDUCER FILE:
const defaultContentReducer = {
content: {
featuresContent: [],
headerContent: [],
}
}
export default (state = defaultContentReducer, action) => {
switch(action.type) {
case 'ADD_FEATURE':
return [
...state.content.featuresContent,
action.features
]
case 'ADD_HEADER':
return [
...state.content.headerContent,
action.header
]
default:
return state
}
}
STORE FILE:
export default () => {
const store = createStore(
combineReducers({
articles: ArticleReducer,
qnaList: QnaReducer,
content: ContentReducer
})
);
return store;
}
The reducer function is supposed to return the next state of your application, but you are doing a few things wrong here, you are returning an array, a piece of the state and not the state object, I would suggest you look into immer to prevent this sort of errors.
Simple fix:
export default (state = defaultContentReducer, action) => {
switch(action.type) {
case 'ADD_FEATURE':
return {...state, content: {...state.content. featuresContent: [...action.features, ...state.content.featuresContent]}}
// More actions are handled here
default:
return state
}
}
If you use immer, you should have something like this
export default (state = defaultContentReducer, action) => {
const nextState = produce(state, draftState => {
switch(action.type) {
case 'ADD_FEATURE':
draftState.content.featuresContent = [...draftState.content.featuresContent, ...action.features]
});
break;
default:
break;
return nextState
}

how to save array object data in redux store

i try to store multiple object in redux store on my react native app, but only one object is save,
i'm new at redux, i try a lot of solutions found on StackOverflow but no one works :/
result i have in my store:
"hives": {"hive_id": 12944, "hive_name": null}
result i want (or something like that) :
"hives": [
1: {"hive_id": 123, "hive_name": "HelloHive"},
2: {"hive_id": 12944, "hive_name": null}]
store:
const middleware = [thunk]
export const store = createStore(persistedReducer, applyMiddleware(...middleware));
export const persistor = persistStore(store);
reducer :
const INIT_STATE = {
hives: [],
}
const hiveReducer = (state = INIT_STATE, action) => {
switch (action.type) {
case SET_HIVES:
return {
...state,
hives: action.payload,
};
[...]
action creator:
export const setHives = hives => {
return {
type: SET_HIVES,
payload: hives,
};
};
action:
export const getHives = () => {
return dispatch => {
axios.get(GET_HIVE_URL, HEADER).then(res => {
const status = res.data.status;
const hives = res.data.hives;
if (status == 'hiveFound') {
for (let i = 0; i < hives.length; i++) {
console.log(hives[i]);
dispatch(setHives(hives[i]));
}
}
});
};
};
and my API send me:
"hives": [
{
"hive_id": 123,
"hive_name": "HelloHive"
},
{
"hive_id": 12944,
"hive_name": null
}
]
and console.log(hives[i]) return :
LOG {"hive_id": 123, "hive_name": "HelloHive"}
LOG {"hive_id": 12944, "hive_name": null}
thanks you
First of all, in your reducer you don't need to use ...state spread operator, since hives seems to be the only one variable in your state there. And second, you are iterating over each element of hives, therefore you are inputting them one by one thus overwriting the previous one. You are not appending it to array. Here's how you need to change your action:
export const getHives = () => {
return dispatch => {
axios.get(GET_HIVE_URL, HEADER).then(res => {
const status = res.data.status;
const hives = res.data.hives;
if (status == 'hiveFound') {
dispatch(setHives(hives));
}
});
};
};
This way it will write the whole array into that variable in redux.
You can try this below so you can store the whole array. assuming you already have the actions.
InitialState
export default {
hives:[]
}
HivesReducer
export default function counter(state = initialState.hives, action) {
switch (action.type) {
case Types.SET_HIVES:
return [...state, action.payload];
default:
return state;
}
}
In your reducer try this :
case SET_HIVES:
return {
...state,
hives: [...state.hives,action.payload],
};
[...]
hope it helps. feel free for doubts

Redux store doesn't update all changes in app.js

such an honor to drop my first question in this community! I'm working on a recipe app where I use Redux to manage states. I'm using async storage to store changes locally. I'm a bit stuck now because my store only applies and stores a few changes instead of the whole recipe.
This is how the data of a recipe looks like (sorry for my Dutch):
{
cardId: 2,
time: "5 minutes",
title: "Wortel-Kokossoep met Dadelroom",
category: "ontbijt",
image: require("./assets/wortel-kokossoep.jpg"),
subtitle: "Gezonde en makkelijke soep!",
caption: "Wortel-Kokossoep met Dadelroom",
description:
"Begin de dag gezond met deze smoothie dat rijk is aan vitamines.",
stepOne: "Stap 1: Voeg alles toe aan de NutriBullet of blender.",
stepTwo:
"Stap 2: Blend twee keer gedurende ongeveer 5 tot 10 seconden en je bent klaar!",
stepThree: "",
stepFour: "",
stepFive: "",
stepSix: "",
stepSeven: "",
stepEight: "",
favorite: false
},
and this is how I implemented Redux in the app.js. Please forgive me for posting the whole code. I'm still a noob, eager to learn everything about Redux and react.
const reducer = (state = initialState, action) => {
switch (action.type) {
case "FAV_RECIPIE":
//const recipie = state.recipies.find(r => (r.cardId = action.id));
const recipieIndex = state.recipies.findIndex(
r => r.cardId === action.id
);
const currentValue = state.recipies[recipieIndex].favorite;
state.recipies[recipieIndex].favorite = !currentValue;
state.recipies = [...state.recipies];
saveRecipes(state.recipies); // save to local storage
return { ...state };
case "SET_LOADED_RECIPIES":
console.warn("!!!!");
if (action.recipies) {
state.recipies = [...JSON.parse(action.recipies)]; // JSON parse to convert string back to list
}
console.log("set recipies");
return { ...state };
case "OPEN_MENU":
return { action: "openMenu" };
case "CLOSE_MENU":
return { action: "closeMenu" };
default:
return state;
}
};
const saveRecipes = async recipies => {
try {
await AsyncStorage.setItem("#VV:Recipes", JSON.stringify(recipies)); // JSON stringify to convert list to string (for storage)
} catch (error) {
// error saving, and that is fine =)
console.log("could not save recipes");
}
};
const store = createStore(reducer, initialState);
store.subscribe(() => {
console.log("store changed", store.getState().recipies);
});
const App = () => (
<Provider store={store}>
<AppNavigator />
</Provider>
);
export default App;
I really hope some of you can help me out! Thanks in advance!
There's a couple of things going wrong in your reducer, but the big thing is doing state-mutations. You want to avoid logic like:
state.recipies[recipieIndex].favorite = !currentValue;
also
state.recipies = [...state.recipies];
This is against redux principles. You never want to directly change values of the state without first making a copy or clone.
So we will go with creating a shallow-copy of state in your reducer and make updates to that instead:
const reducer = (state = initialState, action) => {
switch (action.type) {
case "FAV_RECIPIE":
var newState = {...state}
//const recipie = state.recipies.find(r => (r.cardId = action.id));
const recipieIndex = state.recipies.findIndex(
r => r.cardId === action.id
);
const currentValue = state.recipies[recipieIndex].favorite;
newState.recipies[recipieIndex].favorite = !currentValue;
saveRecipes(newState.recipies); // save to local storage
return { ...newState };
case "SET_LOADED_RECIPIES":
console.warn("!!!!");
var newState = [...state]
if (action.recipies) {
newState.recipies = [...JSON.parse(action.recipies)]; // JSON parse to convert string back to list
}
console.log("set recipies");
return { ...newState };
case "OPEN_MENU":
return { action: "openMenu" };
case "CLOSE_MENU":
return { action: "closeMenu" };
default:
return state;
}
};
Alternatively we can handle this succinctly using .map() which creates a copy for us.
const reducer = (state = initialState, action) => {
switch (action.type) {
case "FAV_RECIPIE":
const updatedRecipes = {
...state,
recipes: state.recipes.map(recipe => {
if (recipe.cardId === action.id) {
return {
...recipe,
favorite: !recipe.favorite
};
} else {
return recipe;
}
})
};
saveRecipes(updatedRecipes)
return {
...updatedRecipes
}
case "SET_LOADED_RECIPIES":
var newState = {...state};
if (action.recipies) {
newState.recipies = [...JSON.parse(action.recipies)]; // JSON parse to convert string back to list
}
return { ...newState };
case "OPEN_MENU":
return { action: "openMenu" };
case "CLOSE_MENU":
return { action: "closeMenu" };
default:
return state;
}
};

React Redux - list of items per some criteria

I faced a problem with React Redux when I need for one page render multiple lists of items from the same API. For example, I have endpoint /items with GET param /items?city=Berlin. I need to render 5 cities lists of items on the frontpage.
Currently I have 1 action to handle API call.
Here is my reducer.js:
...
const initialState = fromJS({
...
items: [],
...
})
export default function reducer (state = initialState, action) {
...
switch (action.type) {
case fetchItemsByCityRoutine.SUCCESS:
return state.update('items', (items) => items.push(...action.payload.data))
...
}
}
saga.js:
function * fetchItemsByCity ({ payload: city }) {
try {
yield put(fetchItemsByCityRoutine.request())
const response = yield call(apiClient.fetchItemsByCity, city)
response.city = city
yield put(fetchItemsByCityRoutine.success(response))
} catch (error) {
yield put(fetchItemsByCityRoutine.failure(extractErrorMessage(error)))
} finally {
yield put(fetchItemsByCityRoutine.fulfill())
}
}
function * watchItemsByCitySaga () {
yield takeEvery(fetchItemsByCityRoutine.TRIGGER, fetchItemsByCity)
}
On the Homepage I render list of cities like this:
const renderCityListSections = () => homepageCityLists.map((city) => <ItemList key={city.cityName} {...city} />)
ItemList component:
class ItemList extends Component {
componentDidMount () {
const { cityName } = this.props
this.props.fetchItemsByCityRoutine(cityName)
}
render () {
const { items, title } = this.props
return (
items.length > 0 &&
<Wrapper>
<SlickSlider>
{items.map((item) => <Item key={item.id} {...item} />)}
</SlickSlider>
</Wrapper>
)
}
}
THE PROBLEM is that current solution makes rerender view too many times because every time I fetch new list for some city it adds to items, so items changes and it leads to trigger rerendering view.
I had a thought to create 5 different Actions for every city, but it's not seems to be reasonable solution.
WHAT is the best approach to render multiple lists of cities on one page?
UPDATE:
So I changed reducer to look like this:
const initialState = fromJS({
...
items: {
Miami: [],
Prague: [],
Melbourne: [],
Venice: [],
Barcelona: [],
},
...
})
export default function reducer (state = initialState, action) {
switch (action.type) {
...
case fetchItemsByCityRoutine.SUCCESS:
return state.updateIn(['items', action.payload.city], (list) => (
list.concat(action.payload.data)
))
...
}
}
so every array is immutable, but again it runs into too much rerendering.
Everybody who has such a problem I ended up with this SOLUTION:
In my reducer I decoupled every item for city like this:
const initialState = fromJS({
...
itemsForBerlin: [],
itemsForAnotherCity: [],
...
})
export default function reducer (state = initialState, action) {
switch (action.type) {
...
case fetchItemsByCityRoutine.SUCCESS:
return state.set(`itemsFor${action.payload.city}`, action.payload.data)
...
}
}

Resources