Promise无法在React useEffect中与Firebase结合使用

时间:2019-05-30 01:56:59

标签: reactjs firebase es6-promise react-hooks

我想像这样在useEffect函数中从Firebase获取数据:

{
    "WebOrderNumber_C": "938276",
    "shipAddress": {
        "add1": "LONDON"
    },
    "items": [{
            "itemName": "B3440S"
        },
        {
            "itemName": "B3440S"
        },
        {
            "itemName": "B3440S"
        }
    ]
}

现在,promise中的第二个console.log将首先显示,然后显示第一个console.log,这意味着请求尚未完成。 我该如何改善代码,以便首先设置请求和状态,然后继续其余操作?

1 个答案:

答案 0 :(得分:0)

export default function Example() { 
    const [data, dataSet] = useState(false)
    const [attendees, setAttendees] = useState(false)

    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await res.json()
      console.log(response);
      dataSet(response)
    }

 useEffect(() => {
      if (!attendees) return 
      fetchMyAPI();
    }, [attendees, newData, listRedux]);


useEffect(() => {
     setAttendees({})
  }, [])

More examples here: