0

I am really new in Hooks and during learning faces many difficulties to switch from the old style.

My old code looks like:

context.js

import React from "react";

const SomeContext = React.createContext(null);

export const withContext = (Component) => (props) => (
  <SomeContext.Consumer>
    {(server) => <Component {...props} server={server} />}
  </SomeContext.Consumer>
);

export default SomeContext;

main index.js

<SomeContext.Provider value={new SomeClass()}>
   <App />
</SomeContext.Provider>

but when I want to access it through with export default withContext(SomeComponent) by this.props.server.someFunc() it showed props is undefined in the classless hook function.

how can I achieve this.props in react hook

Edit:

SomeClass is not React inheriting class and its look like it.

class SomeClass {
  someFunc = (id) => axios('api endpoints')
} 

SomeComponent

const SomeComponent = () => {
...

useEffect(() => {
   this.props.server.someFunc(id).then(...).catch(...)
}, ...)

...
}
6
  • It should be value={<SomeClass/>}, and you better show us the code instead of describing what you trying to do. See How to create a Minimal, Reproducible Example Commented Nov 17, 2020 at 18:32
  • SomeClass is a simple Class without inheriting react. Commented Nov 17, 2020 at 18:34
  • 1
    Just show the code... You don't have this.props in function components. Commented Nov 17, 2020 at 18:36
  • Okay I edit main post Commented Nov 17, 2020 at 18:42
  • Please take a look in React docs, that's not how you use Context, see useContext Commented Nov 17, 2020 at 18:48

1 Answer 1

1

In the regular case, you need to export the Context, then import it and use it within useContext:

export const SomeContext = React.createContext(null);


// Usage
import { SomeContext } from '..';

const SomeComponent = () => {
  const server = useContext(SomeContext);

  useEffect(() => {
    server.someFunc(id);
  });
};

But in your case, since you using HOC, you have the server within the prop it self:

const SomeComponent = (props) => {
  useEffect(() => {
    props.server.someFunc(id);
  });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.