k10a
k10a

Reputation: 1087

Can't fetch firestore data through redux

I'm trying to fetch posts data in firestore with redux. But Actions must be plain objects. Use custom middleware for async actions. error occurs. I don't know why but fetch action may have some issues.

Actually, I had realized with JSON API but Firestore occurs an error when fetching posts.

actions/index.js

export function fetchPosts() {
  return dispatch => {
    postsRef.get().then(querySnapshot => {
      querySnapshot
        .forEach(function(doc) {
          const posts = doc.data();
          return posts;
        })
        .then(posts => {
          dispatch({ type: "FETCH_POSTS", payload: posts });
        });
    });
  };
}

reducers/reducer_post.js

import _ from "lodash";
import { FETCH_POSTS, FETCH_POST } from "../actions";

export default function(state = [], action) {
  switch (action.type) {
    case FETCH_POSTS:
      return action.posts;
    case FETCH_POST:
      return { ...state, [action.payload.data.id]: action.payload.data };

    // ** ES6 is following style **
    // const post = action.payload.data;
    // const newState = { ...state };
    // newState[post.id] = post;
    // return newState;
    default:
      return state;
  }
}

components/posts_index.js

class PostsIndex extends Component {
  componentDidMount() {
    this.props.fetchPosts();
  }
  renderPosts() {
    console.log("this.props.2", this.props);
    return _.map(this.props.posts, post => {
      return (
    );
  }
}

function mapStateToProps(state) {
  return { posts: state.posts };
}

export default connect(
  mapStateToProps,
  { fetchPosts }
)(PostsIndex);

reducers/index.js

import { combineReducers } from "redux";
import PostsReducer from "./reducer_posts";
import { reducer as formReducer } from "redux-form";

const rootReducer = combineReducers({
  posts: PostsReducer,
  form: formReducer
});

export default rootReducer;

App.js

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);

function App() {
  return (
    <Provider store={createStoreWithMiddleware(reducers)}>
      <BrowserRouter>
        <div>
          <Switch>
            <Route path="/posts/new" component={PostsNew} />
            <Route path="/posts/:id" component={PostsShow} />
            <Route path="/" component={PostsIndex} />
          </Switch>
        </div>
      </BrowserRouter>
    </Provider>
  );
}

Upvotes: 0

Views: 117

Answers (1)

k10a
k10a

Reputation: 1087

import { createStore, applyMiddleware, combineReducers } from "redux";
import PostsReducer from "./reducer_posts";
import reduxThunk from "redux-thunk";
import { reducer as formReducer } from "redux-form";

const rootReducer = combineReducers({
  posts: PostsReducer,
  form: formReducer
});

const store = createStore(rootReducer, applyMiddleware(reduxThunk));
export default store;

I have missed ReduxThunk

Upvotes: 1

Related Questions