I
I
Incold2021-03-30 22:17:12
React
Incold, 2021-03-30 22:17:12

Why is the context inside the function different?

Hello! I ran into a problem, I can’t understand why the previous state is in the context inside the function:

Context:

export const WebinarContext = React.createContext({
    correctAnswerPromise: {func: () => {}},
    changePromise: () => {}
})

export const WebinarContextProvider = ({children}) => {
    const [correctAnswerPromise, changePromise] = useState({func: () => {}});

    return (
        <WebinarContext.Provider
            value={{correctAnswerPromise, changePromise}}>
            {children}
        </WebinarContext.Provider>
    )
}


The component in which the context is updated: (is a child of the one below)
...
useEffect(() => {
  context.changePromise({func: (resolve, reject) => {
      return setTimeout(resolve, 4000)
    }})
  }, [])
...


The component in which the function is monitored:
const Lobby = ({lessonData, setEnd}) => {
    const [currentLesson, setCurrentLesson] = useState(lessonData.exercises[0]);
  
   // Получаю контекст (само собой, засунул компоненту в провайдер)
    const context = useContext(WebinarContext);

     // Для тестов сделал эффект, тут всё отрабатывает правильно,т.е. сначала выводит 
     // () => {}, затем (resolve, reject) => {return setTimeout(resolve, 4000)}
    //useEffect(() => {
      //  console.log(context.correctAnswerPromise.func);
    //}, [context.correctAnswerPromise.func])

    const openNextExercise = useCallback((isPauseEnd = false) => {

       //Вот тут основная проблема, чтобы я не делал, убирал useCallback, передавал через props, и т.д., функции пофиг, 
//она всё равно выводит () => {}, соответственно нет вызова resolve, следовательно блок then не срабатывает

        console.log(context.correctAnswerPromise.func);

        new Promise((resolve, reject) => {
            context.correctAnswerPromise.func(resolve, reject)
        })
            .then(() => {
                // Этот блок не выполняется, по причине описанной выше
                ...
            })
    }, [currentLesson, context.correctAnswerPromise.func]);

    return (
     ...
       // Дочерняя компонента, в которой вызывается функция
        <Timer
                ...
               openNextExercise={openNextExercise}
        />
     ...
    )


Why is the original context in the function, and how to fix it. Thanks in advance, for any help?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question