在JavaScript(React Hooks)中的`fetch()` – 我可以在第三个`then`中访问数据吗?

huangapple go评论79阅读模式
英文:

fetch() in js (react hooks) - can I access data in third then?

问题

I'm practicing react and fetch api and I want to send some data but it does not work... Code:

fetch('http://localhost:3003/users', {
  method: 'POST',
  body: JSON.stringify({ name, password }),
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(res => {
  if (res.ok) {
    return res.json();
  }
  throw new Error('Error');
})
.then(user => {
  setUser([...users, user]);
  console.log(user.id);
  setLoggedUserID(user.id);
})
.then(setLoggedUserID(13)) // Check added user's ID
.then(errorUserChange(false)); // Change state and go to /loggedin page

In second then I receive user with name, password and id. When I console.log it, I can see proper id, but when I'm trying to send it with setLoggedUserID function to the state, I receive null. This function works fine in the next then (third), but over there I don't have access to data (above I've hardcoded 13). Whole fetch is in function called after form submission.

Any ideas? Thanks!

英文:

I'm practicing react and fetch api and I want to send some data but it does not work... Code:

fetch('http://localhost:3003/users', {
        method: 'POST',
        body: JSON.stringify({ name, password }),
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => {
          if (res.ok) {
            return res.json();
          }
          throw new Error('Error');
        })
        .then(user => {
          setUser([...users, user]);
          console.log(user.id);
          setLoggedUserID(user.id);
        })
        .then(setLoggedUserID(13)) // Check added user's ID
        .then(errorUserChange(false)); // Change state and go to /loggedin page

In second then I receive user with name, password and id. When I console.log it, I can see proper id, but when I'm trying to send it with setLoggedUserID function to the state, I receive null. This function works fine in the next then (third), but over there I don't have access to data (above I've hardcoded 13). Whole fetch is in function called after form submission.

Any ideas? Thanks!

答案1

得分: 1

你需要将一个函数传递给then()

你试图调用setLoggedUserID(13)并将其返回值作为回调函数传递。

英文:

You need to pass a function to then().

You are trying to call setLoggedUserID(13) and pass its return value as the callback function.

答案2

得分: 1

const res = await fetch('http://localhost:3003/users', {
method: 'POST',
body: JSON.stringify({ name, password }),
headers: {
'Content-Type': 'application/json'
}
});

const user = await res.json();

setUser(prev => [...prev, user]);

setLoggedUserID(user.id); // [loggedUserId, setLoggedUserID] = useState(null)

//

useEffect(() => {
if (loggedUserId) errorUserChange(false);
}, [loggedUserId]);

英文:
const res = await fetch('http://localhost:3003/users', {
    method: 'POST',
    body: JSON.stringify({ name, password }),
    headers: {
      'Content-Type': 'application/json'
    }
  });

const user = await res.json();

setUser(prev => [...prev, user]);

setLoggedUserID(user.id); // [loggedUserId, setLoggedUserID] = useState(null)

//

useEffect(() => {
    if (loggedUserId) errorUserChange(false);
}, [loggedUserId]);

huangapple
  • 本文由 发表于 2020年1月3日 17:13:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定