如何从我的 React 应用程序创建和提交推文

问题描述 投票:0回答:1

我创建了一个带有输入字段和提交按钮的反应应用程序。我想从我的 React 应用程序中发推文。我怎样才能做到这一点。我对此类流程一无所知。请指导我。谢谢你

reactjs api twitter
1个回答
0
投票

使用 axios 将您的 React 应用程序与 Twitter API 集成,允许用户通过使用 API 密钥进行身份验证的表单提交推文,从而启用 POST 请求来创建推文。

import React, { useState } from 'react';
import axios from 'axios';

const TwitterApp = () => {
  const [tweetContent, setTweetContent] = useState('');

  const handleTweetChange = (event) => {
    setTweetContent(event.target.value);
  };

  const handleTweetSubmit = async (event) => {
    event.preventDefault();

    const twitterApiUrl = 'https://api.twitter.com/1.1/statuses/update.json';
    const tweetData = {
      status: tweetContent,
    };

    try {
      const response = await axios.post(twitterApiUrl, tweetData, {
        headers: {
          Authorization: `Bearer YOUR_ACCESS_TOKEN`,
        },
      });

      console.log('Tweet successfully sent:', response.data);
      // Optionally, you can update your UI to show that the tweet was sent.
    } catch (error) {
      console.error('Error sending tweet:', error);
      // Handle error and show appropriate messages to the user.
    }
  };

  return (
    <div>
      <h1>Create and Submit Tweets</h1>
      <form onSubmit={handleTweetSubmit}>
        <textarea
          value={tweetContent}
          onChange={handleTweetChange}
          placeholder="What's happening?"
        />
        <button type="submit">Tweet</button>
      </form>
    </div>
  );
};

export default TwitterApp;

© www.soinside.com 2019 - 2024. All rights reserved.