0

I'm trying to save the data I'm receiving through state but state is always undefined when I try to log it in console to see if it's updating. This is how I'm declaring it

const[lastAction,setLastAction] = useState(undefined); 

And this is when I'm updating it :

document.addEventListener('CLICKED_BUTTON', function (e) {
    var data = e.detail;
    setLastAction(data);
    console.log(lastAction);
    axios.post('http://127.0.0.1:5000/Tracking',{
    message : 'adding',  
    sessionId : localStorage.getItem('TSid'),
    activities : data
  }).catch(function(response){
    console.log(response);
  });
  });

the data I'm receiving is an object. What's wrong with my code so it's not saving ? I'm receiving the data from my content script since I'm developing an extension.

  • Modern Chrome disallows cross-origin requests in content scripts. Do it in the background script: [example](https://stackoverflow.com/a/55292071). – wOxxOm Apr 14 '21 at 16:41
  • setLastAction sets the value into state, but it does not update your lastAction variable. If you console log lastAction immediately after you declare it, you should see `undefined`, then when you click the button, you should see your data. – Charlie Bamford Apr 14 '21 at 16:46
  • @CharlesBamford I tried using promises after posting data and it still shows me undefined. The thing is that I'm using that state to in my component to keep rendering the last action I get from my listener. But it's always undefined. – marwen ericsson Apr 14 '21 at 16:50
  • I didn't say to use promises. Your variable won't update inside the event listener because that's not how set state works. If it's still undefined after doing what I said, I'd check what's in e.detail. – Charlie Bamford Apr 14 '21 at 17:33
  • @CharlesBamford It's not a button that changes the state, I want the state to change whenever I click on the document ( I'm dispatching an event with every click on the document). and I'm changing what I'm rendering depends on what element clicked on the document. – marwen ericsson Apr 14 '21 at 17:45
  • Your event is "CLICKED_BUTTON". Also that's irrelevant. Read my comments. You aren't updating your variable, so it will retain its original value. – Charlie Bamford Apr 14 '21 at 17:50

0 Answers0