Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Organize the app state (front-end) using Context API #254

Open
mar-bi opened this issue Jun 22, 2018 · 3 comments
Open

Organize the app state (front-end) using Context API #254

mar-bi opened this issue Jun 22, 2018 · 3 comments
Assignees

Comments

@mar-bi
Copy link
Contributor

mar-bi commented Jun 22, 2018

Additional resources:
#246 (comment)

@spences10
Copy link
Collaborator

Hi, what states are there that need to be managed?

@mar-bi
Copy link
Contributor Author

mar-bi commented Jun 22, 2018

For now we have the state of components stored in the container components.
Like this:
image

There are almost 2 different purposes for data stored there:

  1. presentational (to show or not some UI),
  2. for handling app data (user search queries, data from API).

@spences10
Copy link
Collaborator

Ok, so can we break it into two different contexts?

In layouts?

Just bear in mind that in Gatsby v2 layouts is being removed, I can't remember the structure now as I'm currently in react-static land 🙃

Anyway I think the general idea is that you split your contexts by grouping them so:

import React from 'react'
// Context is made up of two things
// Provider - Single as close to top level as possible
// Consumer - Multiple have multiple consumers
export const PresentationalContext = React.createContext()

export class PresentationalProvider extends React.Component {
  state = {
    item1: 1,
    item2: 2
  }

  // add function here
  functionHere = () => {
    this.setState({
      item1: 2,
      item2: 3
    })
  }
  render() {
    return (
      <PresentationalContext.Provider
        value={{
          ...this.state,
          functionHere: this.functionHere
        }}
      >
        {this.props.children}
      </PresentationalContext.Provider>
    )
  }
}

and the same for the app data, then when you need the data you wrap the consumer around the main component of where you want to use the data.

@mar-bi mar-bi added next and removed next labels Jul 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants