Async error in typescript react component

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

Async error in typescript react component

问题

I understand your request. Here's the translated code portion:

const AccordionCard = async ({ username }: AccordionCardProps) => {
  const repos = await axios.get(`endpoint/${username}`);
  const { data } = repos;
  return (
    <Card style={{ width: '33vh', marginBottom: '5px' }}>
      <Card.Body>
        <Card.Title style={{ fontSize: '15px' }}>{username}</Card.Title>
        <Card.Text style={{ fontSize: '13px' }}>
          {data ? <p>{data}</p> : null}
        </Card.Text>
      </Card.Body>
    </Card>
  );
}

Please let me know if you need any further assistance.

英文:

I have this react component, that I wish to get a payload from api so that the component can use later.

const AccordionCard = async ({username}:AccordionCardProps) =&gt;{
  const repos = await axios.get(`endpoint${username}`);
  const {data} = repos;
  return(
      &lt;Card style={{ width: &#39;33vh&#39;, marginBottom: &quot;5px&quot; }}&gt;
      &lt;Card.Body&gt;
        &lt;Card.Title style={{fontSize: &quot;15px&quot;}}&gt;{username}&lt;/Card.Title&gt;
        &lt;Card.Text style={{fontSize: &quot;13px&quot;}}&gt;
          {data ? &lt;p&gt; {data} &lt;/p&gt; : null}
        &lt;/Card.Text&gt;
      &lt;/Card.Body&gt;
    &lt;/Card&gt;
  )
}

assuming the data is type string, I found this error when I was using the component
Error: 'AccordionCard' cannot be used as a JSX component.
Its return type 'Promise<Element>' is not a valid JSX element.
Type 'Promise<Element>' is missing the following properties from type 'ReactElement<any, any>': type, props, key.

What I understand, typescript complains about the component type being a promise element because I use async, but if that was the case, then I could get my data from the api. Can I get the payload directly from the react component? If so how?

PS. the reason why I want to do this, because the payload is coming from each username, and I only have access to this endpoint in order to get the data from each username. So instead of predefining the payload at the beginning, I just wish the endpoint is invoked everytime a component is used for that specific username.

Please help. Thanks.

答案1

得分: 1

以下是您要翻译的内容:

"Indeed, you cannot use an async function for a Component. You will need to use a standard function and run the async logic inside a useEffect hook:

const AccordionCard = ({ username }: AccordionCardProps) => {

  // 1) Set a state variable to hold the dynamic data:
  const [data, setData] = useState(null);

  // 2) Run the async &quot;side-effect&quot; inside the useEffect:
  useEffect(() => {
    // 3) Define an async function inside the useEffect callback
    // as the callback cannot be async also
    async function getRepo() {
      try {
        const repos = await axios.get(`endpoint/${username}`);
        setData(repos.data);
        // 4) Handle any network errors.
      } catch (e) {
        setData("Error loading user data.");
      }
    }
    // 5) Init the async function
    getRepo();

  }, []);
  return (
    <Card style={{ width: '33vh', marginBottom: "5px" }}>
      <Card.Body>
        <Card.Title style={{ fontSize: "15px" }}>{username}</Card.Title>
        <Card.Text style={{ fontSize: "13px" }}>
          {data ? <p> {data} </p> : <p>Loading user data...</p>}
        </Card.Text>
      </Card.Body>
    </Card>
  )
}"


<details>
<summary>英文:</summary>

Indeed, you cannot use an async function for a Component. You will need to use a standard function and run the async logic inside a `useEffect` hook:

```jsx
const AccordionCard = ({username}:AccordionCardProps) =&gt;{

  // 1) Set a state variable to hold the dynamic data:
  const [ data, setData ] = useState(null);

  // 2) Run the async &quot;side-effect&quot; inside the useEffect:
  useEffect(()=&gt;{
    // 3) Define an async function inside the useEffect callback
    // as the callback cannot be async also
    async function getRepo(){
      try {
        const repos = await axios.get(`endpoint\${username}`);
        setData( repos.data );
      // 4) Handle any network errors.
      } catch(e){
        setData(&quot;Error loading user data.&quot;);
      }
    }
    // 5) Init the async function
    getRepo();

  },[]);
  return(
      &lt;Card style={{ width: &#39;33vh&#39;, marginBottom: &quot;5px&quot; }}&gt;
      &lt;Card.Body&gt;
        &lt;Card.Title style={{fontSize: &quot;15px&quot;}}&gt;{username}&lt;/Card.Title&gt;
        &lt;Card.Text style={{fontSize: &quot;13px&quot;}}&gt;
          {data ? &lt;p&gt; {data} &lt;/p&gt; : &lt;p&gt;Loading user data...&lt;/p&gt;}
        &lt;/Card.Text&gt;
      &lt;/Card.Body&gt;
    &lt;/Card&gt;
  )
}

huangapple
  • 本文由 发表于 2023年5月21日 21:05:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76300045.html
匿名

发表评论

匿名网友

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

确定