Recently got into normalizing API responses, so that it can be more flatter. I've managed to flat the API response from this
To this:
case FETCH_IMAGES_SUCCESS:
console.log(action.images.entities)
How could iterate it?
Before I was using this.props.images.map()
but now the data is separated.
What should I do to iterate though the images array with the respective nested data?
Reducer.js
import {
UPLOAD_IMAGE_SUCCESS,
POST_COMMENT_SUCCESS,
DELETE_IMAGE_FAILURE,
FETCH_IMAGES_SUCCESS,
POST_COMMENT,
POST_LIKE,
POST_LIKE_SUCCESS,
DISLIKE_POST_SUCCESS,
DELETE_IMAGE_SUCCESS,
} from '../types';
import { REHYDRATE, PURGE, FLUSH }from 'redux-persist'
// We use seamless-immutable but thats for
const initialState = {
images: [],
likeCount: [],
liked: false
};
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_IMAGES_SUCCESS:
console.log(action.images.entities)
// return {
// ...state,
// images: action.images.entities.images,
// ...state.images
// };
default:
return state;
}
};
saga.js
import { normalize, schema } from "normalizr";
import {imageListSchema} from "../schemas";
export function* getImages() {
try {
const images = yield call(api.images.fetchImages);
// debugger;
// console.log(normalize(images, [imageSchema]));
// console.log(images)
const data = normalize(images, imageListSchema )
yield put(fetchImagesSuccess(data));
} catch (error) {
yield put(fetchImageFailure(error.response));
}
}
You can use redux-orm to handle such relational normalized data in frontend.
This involves converting your backend tables to models and then establish relations between them via foreign keys. If you have worked in relational database , it closely models the same principles here in react.
import { Model, fk, many, attr } from 'redux-orm';
class Comment extends Model {//static or instances go here}
Comment.modelName = 'Comment';
// Declare your related fields.
Comment.fields = {
id: attr(),
name: attr(),
userId: fk(//declare foreign key to User model here),
};
Once you have all your models setup, you can then query,update,delete via its API as follows:
Comment.create(response);
Comment.all();
Comment.withId(1).update({ data: 'Nice Book!' });
Comment.all().filter(comment => comment.userId === '123').first().delete();
PS: I am yet to use this in production (switched to GraphQL). Would like to experiment this if I get any opportunity next time