jaimeduque17
jaimeduque17

Reputation: 169

How can I use createContext with TypeScript?

I found a blog where they did it as follows:

import { createContext } from 'react';

type ContextProps = {
    alert: any,
    showAlert: any
};

const alertContext = createContext<Partial<ContextProps>>({});

export default alertContext;

I created another file in which I set up the functions, like this:

const AlertState: SFC<AlertStateProps> = (props) => {

        const initialState = {
            alert: null
        }
    
        const [state, dispatch] = useReducer(alertReducer, initialState);
    
        // Functions
        const showAlert = (msg: any) => {
            dispatch({
                type: SHOW_ALERT,
                payload: {
                    msg
                }
            });
    
            // After 5 seconds clean error message
            setTimeout(() => {
                dispatch({
                    type: HIDE_ALERT
                })
            }, 5000);
        }

    return (  
        <alertContext.Provider
            value={{
                alert: state.alert,
                showAlert
            }}
        >
            {props.children}
        </alertContext.Provider>
    );
}
 
export default AlertState;

But, when I call alertContext in another file, like this:

const Login = (props) => {

const alertContext = useContext(AlertContext);
const { alert, showAlert } = alertContext;

console.log('context', alertContext);
...
}

In the console.log I can see that it takes the empty object and not the properties that are declared in the interface.

enter image description here

Someone knows what can I do?

Upvotes: 1

Views: 874

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

First, Login component should be a child of AlertContext.Provider:

<AlertState>
  <Login/>
</AlertState>

Then you need to pass the context object to createContext, you are passing AlertContext which is not defined.

// You should name context and React component with capital letter
const AlertContext = createContext<Partial<ContextProps>>({});

// Pass `AlertContext`
const {alert,showAlert} = useContext(AlertContext);

Upvotes: 1

Related Questions