Setting Up Redux Thunk and Connecting the Recent Posts Component to Redux
Hi and welcome back to the react app we're building. In the last guide we set up our routes, effectively we made it so when we type in here we can get the results.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So in this guide we're going to start developing the functionality of this application. First thing we want to do is somehow get the search to actually hit our API. So if I head over to the trello board here and I go to the dailysmary.docs.apiary.io basically if you go here we can see the documentation for this api.

large

So forget about the design, we can see that what we need to do is fetch the recent posts. So I guess what we'll do instead of rendering the results that we type in when we type them in here. I guess what we'll do is first get this set of posts.

large

So pretty simple stuff, it's going to take a little bit of redundant code but we are learning here so we can do that. We need the recent post so I'm going to click on this and this is a little bit more involved.

large

We're just going to use Axios which is the same thing basically, just better syntax, quicker syntax so you can learn the concepts better. Now if I copy this and I open postman I recommend you open Postman as well. If you don't have it you can download it, if you don't want to you or you can't for some reason don't worry about it follow along or do it in your browser here, if I paste this in right here. It will return the data in here.

large

Now your data is probably looking something like this.

large

The reason mine's looking like this is because I'm using a chrome extension I can't remember what it's called but it's formatting the data, it's probably called Jason formatter or something if you just google json formatter I have the very first one so just add this and if you don't want to use postman you can just view it like this in here. Now, I'm going to use postman just because I think it's a good tool even though we're not really doing anything specific.

Basically if I open a new one here and I place this in here dailysmarty.com/posts and hit send.

large

We get his data back.

large

Now what we want to do, I'm just going to exit all of these tabs out so you're not confused here. Okay so I just have this one that I typed in here.

large

So I'm going to hit send again, and it gets back the same data so you can see that we have an id, a title, a content, created at, url_for_post, associated_topics and post_links. Back in our design, you can see that we have recent posts, we have the title and what these are down here are the associated topics. Javascript, JavaScript, and JavaScript these are all the same but that's what it is.

large

So we need to get in some data that says the title and the associated topics really really simple. We only need a few things from postman here we just need the Associated topics, and the title. So let's go ahead and start developing this functionality in our app.

I'm going to head over to the app here and let's start by setting up an action in our index.js. So all we need to say is export function fetchRecentPosts and then in here we will basically return a function that takes this faction and then we can perform our request in here.

index.js

export function fetchRecentPosts() {
  return function(dispatch) {
    //perform our request in here.
  }
}

Now we can't do this yet because this is going to require that we install redux thunk which is a type of middleware. So in our terminal let's just say npm install --save redux-thunk hit return on that and let's wait for that to finish and then while that's happening all we have to do is go to bootstripe.js and apply this middleware into our function here.

So in our bootstrap.js we first need to go up here and we need to import thunk. So let's just hit return a couple times and say import thunk from redux-thunk. Then all we have to do is apply the thunk in here and that should set us up.

bootstrap.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Switch, Route } from 'react-router-dom';

import thunk from 'redux-thunk';

import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);

import 'bootstrap/dist/css/bootstrap.css';
import './style/main.scss';

import Home from './components/home';
import Results from './components/results';

function main() {
  ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
      <BrowserRouter>
        <Switch>
            <Route path='/' exact component={Home}/>
            <Route path='/results' component={Results}/>
        </Switch>
      </BrowserRouter>
    </Provider>
    , document.querySelector('.app-wrapper'));
}

document.addEventListener('DOMContentLoaded', main);

Let's go ahead and close bootstrap and go back here to index.js and let's console.log('hello');. Now let's go ahead and go to our application. Actually what we'll do is we need to we need to somehow use this function which means we have to set up our searchBar with redux and what I actually wanted to do is do it in the home.js just because we don't want to preform it in the searchBar because we're going to be using the searchBar in our other results component in our results page.

And this is a problem because we don't want to push to results when we're in another component, but that's for another guide. What we need to know now is that we don't want to perform it in here, we want to perform the request in home.js and that's even off topic anyway because I just remembered we're not trying to fetch anything for this. We're trying to get the recent posts in this guide.

So don't worry about what I just said about the search bar we're focusing on recent posts. We actually want to do it in recentPosts.js. So let's head to recentPosts and let's important actions and set up react-redux in here. So all we have to do is at the top here, we just have to import connect from react redux and then down here we just have to say connect and search bar.

recentPosts.js

import React, { Component } from 'react';

import { connect } from 'react-redux';

class SearchBar extends Component {
  render() {
    return (
      <div className="recent-posts">
        <div className="recent-posts__wrapper">
          <div className="recent-posts__heading">Recent Posts</div>
          <ul className="recent-posts__posts">
            <li>recent post 0</li>
            <li>recent post 1</li>
            <li>recent post 2</li>
          </ul>
        </div>
      </div>
    )
  }
}

Okay that's set up. Now we need to import our actions. So lets say import * as actions from '../actions'. Okay, we have access to our actions, we've set up connect. Now we just need to pass in our map state to props and actions. So what we'll do is we wont pass in maps state to props we'll just pass in null and then put in our actions.

Now later on in the next guide will set up map state to props. But for now we're focusing purely on dispatching the action. So now we have it set up let's just make sure it's running in the browser still. Okay, it's working, I'm going to reload the page just to ensure that it is running again nothing's happening.

Now what we need to do is actually perform this function here fetch recent posts and we can do that at the top here in our componentDidMount. So to return a couple times and type in componentDidMount and then we can say this.props.fetchRecentPosts and if you're confused on how we got this on to Props it's exactly what we just did. We're saying connect our map state to props and our dispatch state to props or whatever it's called, we're connecting our actions to our search bar. That's all you really need to know is that we're connecting these to our props.

So essentially what we need to do, what I first need to do is restart my server because I close it. You don't need to do this if you didn't close yours. OK what I want to do now is explain this a little better. Okay, so actions and now we are saying this.props.fetchRecentPosts which is getting into our actions here and running this. So if we run this we should get a console log that says hello. I'm going to go to the application here. And it says cannot resolve redux-form in components.

large

OK, why is it doing that? I'm just going to check my bootstrap file, I'm going to go back to the app here. localhost:3000 cannot resolve redux-form. I'm just going to re-type git status. Okay, something happened with our package.json. It appears that redux form isn't in here for some reason. If this is happening to you just run npm install --save redux-form and it's important that I don't edit this out because you might accidentally zoom in and mess everything up too. So you got to work through these problems and know that that's part of process.

I just reinstalled redux form, I'm going to check the browser to see if we're running and it still says can't resolve redux form, I'm going to turn off my server and run it again. I'm going to go back in the app here and reload it. Sweet we are running, I was afraid I was going to have to rerecord this but we're looking good.

What were we working on? We were trying to get the recent posts. We have our actions here in index.js. Let's go ahead and go to our recent posts and we know that we're using this component in home. So when we reload it it should just say hello because it's going to mount this component.

Okay, I just noticed a big problem in our app, we're calling the search bar because we copied and pasted the code so let's just call it RecentPosts and lets export RecentPosts. Lets save that and go back here lets reload the page and you'll notice it says hello down here.

large

So it's mounting and it's saying hello which means we have redux thunk set up correctly.

This has been a long guide, there's been a couple errors that messed us up and made it go on longer so what we'll do is we'll commit our code here and then we will hop right into the next guide where we will actually perform our git request to the server here and get this data back and then work with it.

So let's go ahead and commit our code. git status, git add ., and your modified files might look a bit differently just because of what happened during this guide when I was trying to trouble shoot that. git commit -m and I'm going to say for the commit message we'll say "connect recent posts to redux". Okay, I'll catch you in the next guide where we will hop into that request.

We also set up redux thunk so what I can do is say git commit --amend and then I can just change this and say connected recentposts to redux and set up redux-thunk for api requests. Okay, it's just a middleware. I'm going to hit escape colon wq for write quit and it will write and quit out of there and it will amend our commit message.

Okay, I will see you in the next guide where we will hop into that request.

Resources

Source code