Reputation: 27
Now, the "HERE" string is at index 232, after i trigged the button which just add an element to the store array i see "HERE" string at 233, which is incorrect because HERE should keep its index.
I've tried some different approach: purecomponents, copy the data from the store to the component state.
<table border="2">
{this.props.chapters.map((chapter, index) => {
return <TableRow chapter={chapter} key={index} />;
})}
</table>
TableRow
import React, { Component, Fragment } from "react";
class TableRow extends Component {
state = {
title: ""
};
static getDerivedStateFromProps(nextProps, prevState) {
return {
title: nextProps.chapter.title,
id: nextProps.chapter.id
};
}
render() {
return (
<Fragment>
<tr>
<td>
<input
type="text"
value={this.state.title}
onChange={e => {
this.setState({ ...this.state, title: e.target.value });
}}
/>
</td>
<td>{this.state.id}</td>
<td>{this.props.exposure}</td>
</tr>
</Fragment>
);
}
}
export default TableRow;
The reducer, but POST_CHAPTER works fine, the array is dispatched correctly, the problem is React.
import {
FETCH_ALL_CHAPTER,
POST_CHAPTER,
PUT_CHAPTER,
DELETE_CHAPTER
} from "../actions/ChapterActions";
const INITIAL_STATE = {
chapter_list: []
};
export default function chapterReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_ALL_CHAPTER:
return { ...state, chapter_list: [...action.payload] };
case DELETE_CHAPTER:
let chaptersCopy0 = state.chapter_list.filter(
s => s.uuid !== action.payload
);
return {
...state,
chapter_list: [...chaptersCopy0]
};
case POST_CHAPTER:
return {
...state,
chapter_list: [
...action.payload,
...state.chapter_list
]
};
case PUT_CHAPTER:
let indexToSub = state.chapter_list.findIndex(
s => s.uuid === action.payload.uuid
);
let chaptersCopy1 = [...state.chapter_list];
chaptersCopy1[indexToSub] = action.payload;
return {
...state,
chapter_list: [...chaptersCopy1]
};
default:
return state;
}
}
The action:
export function postChapter(customer_uuid, assessment_uuid, chapter_data) {
let url = `${ROOT_URL}/x/${customer_uuid}/assessmentcontainers/${assessment_uuid}/chapters/`;
return dispatch => {
return axios
.post(url, chapter_data)
.then(res => {
dispatch({
type: POST_CHAPTER,
payload: res.data
});
dispatch(
notifSend({
message: "Created",
kind: "success",
dismissAfter: 2000
})
);
return res;
})
.catch(error => {
console.log(error);
if (error !== UNAUTHORIZED_ERROR)
dispatch(
notifSend({
message: messageStatus(error),
kind: "danger",
dismissAfter: 2000
})
);
return { status: error.status };
});
};
}
Upvotes: 0
Views: 53
Reputation: 1258
You're inserting the new chapter at the start of the array which changes the index of all the following elements.
{
...state,
chapter_list: [
...action.payload,
...state.chapter_list
]
};
Upvotes: 1