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

useSelector() in dependency package causes "could not find react-redux context value" #1489

Closed
aforty opened this issue Jan 3, 2020 · 18 comments

Comments

@aforty
Copy link

aforty commented Jan 3, 2020

What is the current behavior?
So I'm not sure if this is a bug or intended behavior but here is the scenario. I have encapsulated all of our frontend data-layer code and utilities into a separate package that I can then add as a dependency to our various frontend projects (mobile, web, backend, other dashboards, etc).

Problem: when I use useSelector() from within the dependency package (used in a custom hook) it doesn't seem to receive the redux store I passed into the <Provider /> from the main application. I end up with the error "Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a <Provider>".

If I move the custom hook (and it's useSelector() call) to the main application then everything works as intended. I've tried to make sure that the versions of react and react-redux match both in the main application and dependency package but to no avail.

What is expected behavior?
I would like to be able to encapsulate the useSelector() hook into packages and share them.

Versions

// package.json

"react": "16.9.0",
"react-native": "0.61.5",
"react-redux": "^7.1.3",
"redux": "^4.0.5",
$ npm ls react react-redux redux

@mycompany/mobile@0.1.0 /Users/aforty/Code/mycompany-mobile
├─┬ @mycompany/common@0.0.1
│ ├── react@16.9.0  deduped
│ ├── react-redux@7.1.3  deduped
│ └── redux@4.0.5  deduped
├── react@16.9.0
├── react-redux@7.1.3
└── redux@4.0.5
@markerikson
Copy link
Contributor

Yep, that dependency tree shows the problem. Any time there's multiple copies of React or React-Redux in your tree, things are almost definitely going to break. Your own package should likely declare them as peerDependencies (and probably devDependencies), not dependencies. It's the app project's responsibility to make sure they exist at runtime.

@aforty
Copy link
Author

aforty commented Jan 4, 2020

Oh yeah I didn’t think of that. Thanks for the tip!

@gre
Copy link

gre commented Jan 6, 2020

I've noticed this bug can also appear, not because of dups, but because of es vs lib entry point

In my React Native bundle I can notice in the source code there are twice the lib under different paths:

“node_modules/react-redux/lib/....”
“node_modules/react-redux/es/....”

I'm not yet sure why and how this happens, if you guys have any idea of a root cause, I might hack something in the node_modules to solve it in my end (like patching the package.json to not mention the "module" entry for now)

@markerikson
Copy link
Contributor

We ship the compiled code in both CommonJS and ESM module formats, because both are useful in different build setups.

Whatever bundler you're using should only be using one of those two folders.

@gre
Copy link

gre commented Jan 6, 2020

mmh so I'm using React Native default bundler. (react-native start)

@markerikson
Copy link
Contributor

Nothing about the build output format has changed in quite a while, so I don't have any answers on why you might be experiencing issues.

@gre
Copy link

gre commented Jan 6, 2020

Ok thanks. If I don't foresee any solution, I'll try to make a minimal reproductible example and send an issue to appropriate place (either react-native or metro)

@gre
Copy link

gre commented Jan 6, 2020

Ok i've spot the problem, we had wrong import that was doing import connect from "react-redux/es/connect/connect" due to automatic import IDE.. we will make sure no devs use magic importer, this is too error prone.

if it helps anyone passing by.

thanks

@markerikson
Copy link
Contributor

Yep, I've seen a couple other people mention that same thing happening.

@brayanL
Copy link

brayanL commented Feb 19, 2020

@Firanolfind exactly where in the webpack file should i add 'react-redux': require.resolve('react-redux')?

@sijonelis
Copy link

sijonelis commented May 8, 2020

@brayanL you can do it here:

...
resolve: {
    ...
    alias: {
      'react-redux': require.resolve('react-redux'),
    },
  },

@Luckygirlllll
Copy link

I'm also having this error, is there any updates about this issue?

@markerikson
Copy link
Contributor

Per the comments I made earlier, there are no "updates". This is not a bug in React-Redux - it's always an issue with your build environment.

@gkatsanos
Copy link

gkatsanos commented Sep 4, 2020

Same problem here.

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
configure({ adapter: new Adapter() });
import configureStore from "redux-mock-store";
const mockStore = configureStore();
let store = mockStore(initialState);
import CarPhoto from "../CarPhoto";

import React from "react";
import { shallow } from "enzyme";

it("renders without crashing", () => {
  shallow(
    <Provider store={store}>
      <CarPhoto />
    </Provider>
  );
});


    console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Uncaught [Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>]

simple CRA app, "react-scripts": "3.4.1",

component:

import React, { useEffect, useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import CarPhoto from "./CarPhoto";
import { getCar } from "./carActions";
import { selectPhotos } from "./carSelectors";
import Container from "@material-ui/core/Container";
import { Helmet } from "react-helmet";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";

const CarPhotos = (props) => {
  const useStyles = makeStyles((theme) => ({
    container: {
      paddingTop: theme.spacing(2),
      paddingBottom: theme.spacing(2),
    },
  }));
  const classes = useStyles();
  const dispatch = useDispatch();

  const photos = useSelector((state) => selectPhotos(state));
  const fetchCar = useCallback(() => {
    return dispatch(getCar());
  }, [dispatch]);

  useEffect(() => {
    fetchCar();
  }, [fetchCar]);

  if (photos && photos.length) {
    return (
      <Container maxWidth="lg" className={classes.container}>
        <Helmet>
          <meta charSet="utf-8" />
          <title>Photos</title>
        </Helmet>
        <Grid container spacing={2}>
          <Grid item>
            <img src="logo.png" />
          </Grid>
          <Grid item display="flex">
            <Typography variant="h2" component="h2">
              Coding Challenge
            </Typography>
          </Grid>
        </Grid>
        <Grid container spacing={2} justify="center">
          {/* using the array index as key as it will probaly wont change and we're not doing table sorting or filtering */}
          {photos.map((photo, index) => (
            <Grid key={index} item xs={12} sm={6} md={3}>
              <CarPhoto photo={photo} withReadMoreButton={true} />
            </Grid>
          ))}
        </Grid>
      </Container>
    );
  } else {
    return null;
  }
};

export default CarPhotos;

@LucaHermann
Copy link

Hi how should i get rid of this ?

 ▶ npm ls react react-redux redux
zts@0.1.0 /Users/luca/Code/Code_Taff/ts
├─┬ @types/react-redux@7.1.15
│ └── redux@4.0.5 
├─┬ gatsby@2.30.1
│ ├─┬ gatsby-cli@2.17.0
│ │ └── redux@4.0.5  deduped
│ └── redux@4.0.5  deduped
├── react@16.14.0 
└── react-redux@7.2.2 

Coz i think this lead me to have a lot of bulls**t in my app and is for the work not for a side project

@markerikson
Copy link
Contributor

Get rid of... what, exactly?

This appears to be an NPM usage question, and isn't something we can support here. Please ask that in a relevant venue.

@anastasiap
Copy link

I made it work by updating all relevant libs - redux and react-redux.

Mind, you'll need to remove relevant aliases, update libs, then delete node_modules, then install it all over again. Otherwise, a
whole new bunch of unpleasantries will come up.

@reduxjs reduxjs deleted a comment from Anmolreshi May 18, 2021
@reduxjs reduxjs locked as resolved and limited conversation to collaborators May 18, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

10 participants