Skip to content

Instantly share code, notes, and snippets.

@benknight
Last active August 9, 2019 06:22
Show Gist options
  • Save benknight/87cb6cf4ae3e883e86bf81c636e47755 to your computer and use it in GitHub Desktop.
Save benknight/87cb6cf4ae3e883e86bf81c636e47755 to your computer and use it in GitHub Desktop.
Using mock data to represent a best-case-scenario local data schema, then mapping API data to that
// src/mocks/Posts.js
export default [
{
id: 'p0',
title: 'Post 0',
body: 'Blah blah blah',
},
// etc.
];
// src/api/getPosts.js
export default async function getPosts() {
if (process.env.NODE_ENV === 'development') { // Or some other flag
// Return raw mock data
const { default: posts } = await import('../mocks/Posts');
return posts;
}
const posts = await fetch('/posts');
// Now map posts API data to the same data structure as mock data
posts.map(p => ({
title: p.randomFieldName,
body: p.otherRandomFieldName,
// and so on...
});
return posts;
}
// src/actions/fetchPosts.js
// If you're using Redux, it might looks something like this:
import getPosts from '../api/getPosts';
export default dispatch => {
const posts = getPosts();
return dispatch({ type: 'RECEIVE_POSTS', posts });
};
// src/components/Posts.js
import React, { useEffect, useState } from 'react';
import fetchPosts' from '../actions/fetchPosts';
const Posts = ({ dispatch }) => {
const { posts, setPosts } = useState(null);
useEffect(() => {
const posts = await dispatch(fetchPosts());
setPosts(posts);
});
// render posts...
return <div />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment