GithubHelp home page GithubHelp logo

resir014 / react-redux-typescript-example Goto Github PK

View Code? Open in Web Editor NEW
587.0 18.0 148.0 1.91 MB

Demonstrating the common patterns when using React, Redux v4, and TypeScript.

Home Page: https://resir014.xyz/posts/2018/07/06/redux-4-plus-typescript/

HTML 2.17% TypeScript 97.35% JavaScript 0.48%
react redux typescript starter-kit

react-redux-typescript-example's Introduction

react-redux-typescript-example

Demonstrating the common patterns when using React, Redux v4, and TypeScript.

Example deployment: (link)

Welcome to the Redux 4 + TypeScript 3.3 example! This example site shows you the ideal project structure, recommended libraries, as well as design pattern on writing type-safe React + Redux app with TypeScript.

This project is intended as a supplement to this post. To demonstrate it, I created a website which pulls data from the OpenDota API, and display information like professional teams, heroes, as well as top players by hero. This will also demonstrate how to structure your stores for each feature/module in a Redux-enabled app.

This project was bootstrapped with Create React App.

Getting started

A Node.js 8.0.0+ setup with yarn is recommended.

# install dependencies
yarn

# ...or if you'd like to use npm instead
npm install

# serve with hot reload at localhost:3000
yarn start

# build for production
yarn build

react-redux-typescript-example's People

Contributors

andrewcraswell avatar cancerberosgx avatar iheartweb avatar parthopdas avatar resir014 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-redux-typescript-example's Issues

Migrating to latest versions - [ react-redux & connected-react-router ]

Hello, I got to learn a lot by following this example, however if I try to use it with the latest:

"react-redux": "^6.0.0"
"connected-react-router": "^6.2.2"

I get errors everywhere and of course I've been looking for a proper way to migrate on their docs but the docs are not considering typescript and I am still learning.

I was just wondering if you could give some pointers to migrate it to the latest versions.

Fetch running on localhost fails

api.opendota.com/api/heroStats:1 Failed to load resource: the server responded with a status of 403 ()
:1234/#/heroes:1 Access to fetch at 'https://api.opendota.com/api/heroStats' from origin 'http://localhost:1234' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
2api.opendota.com/api/teams:1 Failed to load resource: the server responded with a status of 403 ()
:1234/#/teams:1 Access to fetch at 'https://api.opendota.com/api/teams' from origin 'http://localhost:1234' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
2api.opendota.com/api/heroStats:1 Failed to load resource: the server responded with a status of 403 ()
:1234/#/heroes:1 Access to fetch at 'https://api.opendota.com/api/heroStats' from origin 'http://localhost:1234' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

^Versions in package.json

I guess it's better to remove ^ symbol in the package.json because if the newer version with new API of any package will be released, it can crash app while deploying it on a local machine. Removing ^ symbol you can be sure that everything will run ok at anyone local computer.

Question about ConnectedReduxProps

In the example you have the following code (similar). How is Dispatch being passed by default with connect() if you are already doing mapDispatchToProps(), which is supposed to replace Dispatch?

// Additional props for connected React components. This prop is passed by
// default with `connect()`
export interface ConnectedReduxProps<A extends Action = AnyAction> {
  dispatch: Dispatch<A>;
}

Then let's say you have a component with following props interfaces
interface PropsFromState {
  loading: boolean;
  user: User;
}

// We can use `typeof` here to map our dispatch types to the props, like so.
interface PropsFromDispatch {
  initializeRequest: typeof initializeRequest;
}
type AllProps = PropsFromState & PropsFromDispatch & ConnectedReduxProps;

And the mapping functions:
const mapStateToProps = ({ platform }: ApplicationState) => ({
  user: platform.user,
  loading: platform.loading
});

// mapDispatchToProps is especially useful for constraining our actions to the connected component.
// You can access these via `this.props`.
const mapDispatchToProps = {
  initializeRequest
};

// Now let's connect our component!
// With redux v4's improved typings, we can finally omit generics here.
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Main);

Code splitting with react-loadable [Question]

I've just started a new project at work and have implemented the patterns described in this repository. We're starting with one of our internal React starter kits which has Code Splitting w/ Webpack 4 and TypeScript preconfigured using react-loadable. I thought it was cool that the comments in this repo mentioned this approach as recommended. Has anyone done this though? I ran into a lot of errors when configuring my RouteConfig and using ConnectedReduxProps. I was able to resolve the problem just by removing ConnectedReduxProps from the compound type when creating my components. This of course, is not the best solution.

export const routeConfig: RouteConfig[] = [
{
    component: Loadable({
      loader: () => import("./pages/Home/Home"),
      loading: Loading
    }),
    path: "/",
    exact: true
  }
];

For reference, the error is being highlighted on the component property, and this is what I'm getting:

(property) RouteConfig.component?: React.ComponentClass<{} | RouteConfigComponentProps<any>, any> | React.StatelessComponent<{} | RouteConfigComponentProps<any>> | undefined
Type '(ComponentClass<Pick<IAllProps, "dispatch">, any> & LoadableComponent) | (StatelessComponent<Pick<IAllProps, "dispatch">> & LoadableComponent)' is not assignable to type 'ComponentClass<{} | RouteConfigComponentProps<any>, any> | StatelessComponent<{} | RouteConfigComponentProps<any>> | undefined'.
  Type 'ComponentClass<Pick<IAllProps, "dispatch">, any> & LoadableComponent' is not assignable to type 'ComponentClass<{} | RouteConfigComponentProps<any>, any> | StatelessComponent<{} | RouteConfigComponentProps<any>> | undefined'.
    Type 'ComponentClass<Pick<IAllProps, "dispatch">, any> & LoadableComponent' is not assignable to type 'ComponentClass<{} | RouteConfigComponentProps<any>, any>'.
      Types of property 'getDerivedStateFromProps' are incompatible.
        Type 'GetDerivedStateFromProps<Pick<IAllProps, "dispatch">, any> | undefined' is not assignable to type 'GetDerivedStateFromProps<{} | RouteConfigComponentProps<any>, any> | undefined'.
          Type 'GetDerivedStateFromProps<Pick<IAllProps, "dispatch">, any>' is not assignable to type 'GetDerivedStateFromProps<{} | RouteConfigComponentProps<any>, any>'.
            Types of parameters 'nextProps' and 'nextProps' are incompatible.
              Type 'Readonly<{}> | Readonly<RouteConfigComponentProps<any>>' is not assignable to type 'Readonly<Pick<IAllProps, "dispatch">>'.
                Property 'dispatch' is missing in type 'Readonly<{}>' but required in type 'Readonly<Pick<IAllProps, "dispatch">>'.ts(2322)
Home.tsx(27, 3): 'dispatch' is declared here.
Home.tsx(27, 3): 'dispatch' is declared here.
index.d.ts(17, 5): The expected type comes from property 'component' which is declared here on type 'RouteConfig'

Is there interest in updating these examples to show code splitting of Redux and Sagas? I was looking at some Microsoft open source to simplify this solution.

Either way, when we're done with implementing this pattern in our app I'll likely submit a PR with some of our smaller tweaks we felt were an improvement. At the very least it would be helpful to get constructive criticism on the approach.

Question about window.INITIAL_REDUX_STATE

Hi there,

Thank you for this great sample, is helping me a great deal to have a good first implementation of Redux on my React app since I never used Redux previously.

I'm running into an issue, on your root file index.tsx you are getting the initialState with window.INITIAL_REDUX_STATE.
On my app gives an error, has no idea what it is and just says the property doesn't exist.

I've done some quick search and this seem to be something for server side rendering?
My problem is that my app is a SPA that only runs client side, I don't have any server side, I simply provide the website from a CDN that feeds from a storage account on Azure pretty much.

What would it be the best way for me to get the store initialState to provide to the configureStore() method?

Thank you very much,
Ralms.

Switch from parcel to Create React App (CRA)

Based on @parthopdas' suggestion on #8 I think it'd be better if we switch the initial project setup from parcel to CRA 3.0.

  • I initially set up this repo with parcel because it was originally only meant for an example for my blog post, but since people might be using this template as a starter point, CRA seems like a good choice to reduce the barrier to entry.
  • CRA 2.0+ already supports TypeScript out of the box anyway.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.