question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

React useEffect / useState not recognizing state values when working within a GraphQL subscription

See original GitHub issue

Do you want to request a feature or report a bug? bug? (maybe) or I could be using the hook wrong

What is the current behavior? When using useEffect, the current state value is not available in the state, only the old state value is available.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn’t have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

https://codesandbox.io/s/5xwjrjwo74

What is the expected behavior? State is available in memory

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

16.7.0-alpha.0

code.zip

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:6

github_iconTop GitHub Comments

15reactions
AyWacommented, Oct 31, 2018

Maybe we do have to subscribe/unsubscribe on every render…

@thchia I think there is multiple way to achieve that. One way is with reducer, but I guess there is other way too ? https://codesandbox.io/s/03l8z5m8nw

const initialState = { todoList: [] };

function reducer(state, action) {
  switch (action.type) {
    case "set":
      return { todoList: action.payload };
    case "add":
      return { todoList: [...state.todoList, action.payload] };
  }
}

export function useSubscription() {
  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(async () => {
    const todoData = await API.graphql(graphqlOperation(query));
    dispatch({ type: "set", payload: todoData.data.listTodos.items });
  }, []);

  useEffect(() => {
    const subscriber = API.graphql(graphqlOperation(subscription)).subscribe({
      next: data => {
        const {
          value: {
            data: { onCreateTodo }
          }
        } = data;
        dispatch({ type: "add", payload: onCreateTodo });
      }
    });
    return () => subscriber.unsubscribe();
  }, []);

  return state.todoList;
}
1reaction
ayalcommented, Jan 23, 2020

@AyWa 's solution worked for me (i.e using a reducer)

However I was able to solve a similar issue (subscribing once in useEffect and updating state in callback) while still using useState(), alongside with the “function updater” option of the state update function

as mentioned here: https://reactjs.org/docs/hooks-reference.html#functional-updates

Read more comments on GitHub >

github_iconTop Results From Across the Web

Graphql subscriptions inside a useEffect hook doesn't access ...
I tried it with both useState , as well as storing/retrieving it from redux, nothing is working. reactjs · apollo · react-apollo ·...
Read more >
Setting React State after useQuery? : r/graphql - Reddit
I am assuming because useEffect gets called and data doesn't exist yet, so it gets skipped. Navigating back and the data populates. Ideally, ......
Read more >
Hooks - Apollo GraphQL Docs
This property is part of Apollo Client's React integration, and it is not available in the core ApolloClient API. The default value is...
Read more >
Common React Hooks Mistakes You Should Avoid
1. Changing the Hooks Invocation Order · 2. Using useState when Re-Render is not Required · 3. Handling Actions via useEffect · 4....
Read more >
Dangers of using Objects in useState & useEffect ReactJS ...
Another solution would be to simply not use objects in an useState hook. You could use the useState hook per each property of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found