Twitter API and React - javascript

I'm just messing right now with react and thought I would try to make an app that could search for tweets. I basically just follwed the npm twitter examples but I can't get it to work. Here's what I have:
import React, { Component } from 'react';
import Twitter from 'twitter';
import config from './config.js'
class App extends Component {
constructor(){
super();
this.Client = new Twitter(config);
this.searchTwitter = this.searchTwitter.bind(this);
}
searchTwitter(){
this.Client.get('search/tweets', {q: 'node.js'}, function(error, tweets, response) {
console.log(tweets);
});
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">The Test App</h1>
</header>
<button style = {{height: "50px", width: "150px"}} onClick = {this.searchTwitter}> CLICK ME </button>
</div>
);
}
}
It's just a quick test where you click the button and it searches for tweets and logs them to the console. The problem is I just get 'undefined' every time and I have checked the keys and tokens so I don't think that's the issue.
I've never tried to use this API so any help is very appreciated

It seems that the twitter api doesn't support CORS request, So we cannot make any calls to the api through the browser, hence its not working for you.
Please refer to the below link for more details:
https://twittercommunity.com/t/will-twitter-api-support-cors-headers-soon/28276/4

Related

Trying to display text, but no luck. However, I check my console and see empty divs with p tags. App is not breaking

I am in the process of working on a joke app, which I am building from scratch by myself with no tutorial. Right now, there is a component SportsJokesApi, that pulls in the data from a local json folder (SportsJokesData) I created. This is how it is set up:
const SportsJokesData = [
{
id: "1",
question: "What did the baseball glove say to the ball?",
answer: "Catch ya later!"
}
]
export default Sports Jokes Data
On the landing page, when the user selects the Sports Jokes category, they will be taken to a new page which will display jokes related to sports. Right now, you need to click the button (Click here for a joke) in order for the first joke to display. I would love for the first random joke to already be displaying when the user selects this category and gets taken to that page for the first time.
This is how I have the component set up. In my initial approach I created a separate function called getInitialJoke, which returns a random joke. Then in the render, I created a variable called const {initialJoke} which is this.getInitialJoke(); and then the joke would be displayed. Since state update is asynchronous, I did some safety checking by using initialjoke?.answer. When I go back and run the app, no joke appears and the text does not show up. However, I do see new divs with empty p tags on console. Does anyone know what could be wrong and how I can fix this? Again, I want a joke to already be displaying. The way it is set up in this component, you have to click on the Click Here for a Joke button in order to see the first joke.
import React from 'react'
import SportsJokesData from '../data/SportsJokesData';
import { Link } from 'react-router-dom';
import './Buttons.css';
const initialState = {
randomJoke: {}
};
class SportsJokesApi extends React.Component {
constructor(props) {
super(props);
this.getRandomJoke = this.getRandomJoke.bind(this);
this.state = initialState;
}
getInitialJoke() {
return SportsJokesData[(SportsJokesData.length * Math.random()) << 0];
}
getRandomJoke() {
this.setState({
randomJoke: SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
});
}
render() {
const {randomJoke} = this.state;
const {initialJoke} = this.getInitialJoke();
return (
<React.Fragment >
<div>
<p>{initialJoke?.question}</p>
</div>
<div>
<p>{initialJoke?.answer}</p>
</div>
<div className="flex">
<p>{randomJoke.question}</p>
</div>
<div className="flex">
<p>{randomJoke.answer}</p>
</div>
<div className="flex">
<button class="btn joke" onClick = {this.getRandomJoke}>Click here for joke </button>
</div>
<div className="flex">
<Link to="/ProgrammingJokes">
<button className="btn programming">Programming Jokes</button>
</Link>
</div>
<div className="flex">
<Link to="/DadJokes">
<button className="btn dad">Dad Jokes</button>
</Link>
</div>
<div className="flex">
<Link to="/SpanishJokes">
<button className="btn spanish">Chistes en ñ</button>
</Link>
</div>
<div className="flex">
<Link to="/">
<button className="btn home">Home Page</button>
</Link>
</div>
</React.Fragment >
);
}
}
export default SportsJokesApi;
Perhaps you could call the initialJoke() function in one of the React lifeCycle Events, for example with something like this:
// Add this to your code fellow.
componentDidMount() {
this.getInitialJoke();
}
For more information on the life cycle events and how they work, have a look at this great article, buddy.
React: Component Lifecycle Events

Firebase switch header option with onAuthStateChanged

I'm sorry if my question has already asked.
I am a beginner on react and I really want to learn how to do this and understand.
I use Firebase on my React.JS project and i want switch a part of header when the user has connected or not.
I think using the conditional-rendering but on the firebase function after the (if) does not allow me to do setState().. or i have an error
So I would be very happy if we could help me or give me a track of where to look for the answers !
class Header extends Component {
state={
connected: null
}
render(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
} else {
}
});
return (
<div className="backgroundheader">
<div className="liensheader">
<a href="/" className="lili" style={{textDecoration: "none"}}>Home</a>
<a href="/event" className="lili" style={{textDecoration: "none"}}>Manifestations</a>
<a href="/commerces" className="lili" style={{textDecoration: "none"}}>Commerces</a>
<a href="/tips" className="lili" style={{textDecoration: "none"}}>Tips</a>
</div>
{/* options header when the user is disconnect */}
{/* <Deader /> */}
{/* options header when the user is connected */}
{/* <Ceader /> */}
</div>
);
}
};
export default Header;
Thank's you and sorry for my bad english :/
The onAuthStateChanged fires asynchronously, so you can't directly use it inside your render method. Whenever you have a situation like this, the solution is to put the asynchronous value into the state, and then use the state in the render method.
So something like:
class Header extends Component {
state={
connected: null
}
componentDidMount() {
firebase.auth().onAuthStateChanged(function(user) {
setState({ user: user });
});
}
render(){
return (
<div className="backgroundheader">
<div className="liensheader">
<a href="/" className="lili" style={{textDecoration: "none"}}>Home</a>
<a href="/event" className="lili" style={{textDecoration: "none"}}>Manifestations</a>
<a href="/commerces" className="lili" style={{textDecoration: "none"}}>Commerces</a>
<a href="/tips" className="lili" style={{textDecoration: "none"}}>Tips</a>
</div>
{ user ? <Deader /> : <Ceader /> }
</div>
);
}
};
export default Header;
Also see:
Firebase storage: download images to and put to img src in React map. The same problem of asynchronously loaded data, but then with getting the download URL of images in Cloud Storage.
How to update Firebase data to the React application in realtime. This highlights the same problem of asynchronously loaded data, but now with getting JSON data from the Realtime Database.

How to make a Dynamic dropdown done in React with SQL database

I'm building a react app using facebook's:
https://github.com/facebookincubator/create-react-app
I´m new to react and I havent done a dropdown menu before. I have read a lot in the web and I figure I maybe need to use the select and options tags?
I want to have 4 image buttons as I call Main menu (three of the buttons will be able to navigate directly to the picked page).
The last image button will show an undermenu with 12 options pages to go to.
Option Option Option Option
Undermenu
12 options
I´m unsure where I shall begin, right now I have done some coding before I knew I needed to connect it to the SQL database.
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import DropdownMenu from "./components/DropdownMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<DropdownMenu />
<p className="TEST"> lorem imsum </p>
</div>
);
}
}
export default App;
DropdownMenu.js component:
import React from 'react';
import main_menu_home from '../images/Buttons/main_menu_home.png';
import main_menu_dragons from '../images/Buttons/main_menu_dragons.png';
import main_menu_dragon_test from '../images/Buttons/main_menu_dragon_test.png';
import main_menu_fortune_cookie from '../images/Buttons/main_menu_fortune_cookie.png';
const DropdownMenu = props => (
<header>
<nav>
<div className="dragonMenu-container">
<div className="dragonMenu">
<ul>
<li>
<img
id="Home"
className="Main_home"
src={main_menu_home}
alt="Home_button_image"
/>
</li>
<li>
<img
id="Dragons"
className="Main_Dragons"
src={main_menu_dragons}
alt="Dragons_button_image"
/>
</li>
<li>
<img
id="Dragon_test"
className="Main_Dragon_test"
src={main_menu_dragon_test}
alt="Dragon_test_button_image"
/>
</li>
<li>
<img
id="Fortune_cookie"
className="Main_fortune_cookie"
src={main_menu_fortune_cookie}
alt="Fortune_cookie_button_image"
/>
</li>
</ul>
</div>
</div>
</nav>
</header>
);
export default DropdownMenu;
Here the code just display four images which it gets from the images/Buttons folder. Maybe you don´t need so many imports and can get all the images with just a proper link to the image but I donno how to.
I think I need a global variable that pointing where all my images are so I can just have to invoke said variable to access the folder where the pictures are.
Ideas?
But back to the Dropdown problem:
I guess I need to create a table in my Sql?
But I donno how.
My problem is that I think of all things at the same time I need to do, but can´t easy myself to do one thing at the time.
I have more code for when I before fetched all from another table if you want to see that code as well.
Any questions, feel free to ask away :)
// Dragoness
UPDATED 18 sep 2019:
Right now, I have come this far:
I can now talk to the SQL database with react and print out some data from the SQL database itself. My problem now is that I just see broken images, does anyone have a solution for my problem?
What I see on the browser
My SQL database menus table with 4 columns
What I wrote in the browse tag to enter my data
Where I have MainMenu.js file and where I want the Buttons images from
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import DropdownMenu from "./components/DropdownMenu";
import MainMenu from "./components/MainMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<DropdownMenu />
<MainMenu />
<p className="TEST"> lorem imsum </p>
<div><img src='./images/Buttons/main_menu_home.png'/> </div>
</div>
);
}
}
export default App;
fetchMenu.php:
<?php
/* This file fetches current menus . */
include_once 'database.php';
$statement = $pdo->prepare("SELECT * FROM menus ORDER BY picUrl ASC");
$statement->execute();
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data, JSON_PRETTY_PRINT);
?>
MainMenu.js:
import React, { Component } from 'react';
import "../App.scss";
class DropDownMenu {
id: 0;
picUrl: "";
linkUrl: "";
isSubmenu: "";
}
class MainMenu extends Component {
constructor(props) {
super(props);
this.state = {
allMenus: []
}
}
fetchAllMenus = () => {
fetch("http://localhost/dragonology/server/fetchMenu.php")
.then(response => response.json())
.then(data => {
console.log(data);
this.setState({ allMenus: data });
});
}
componentDidMount() {
this.fetchAllMenus();
}
render() {
let menu = this.state.allMenus.map((item) => {
return (<div key={item.id}><img src={item.picUrl} alt="dropdownmenu_main_and_under"/> - {item.linkUrl} - {item.isSubmenu}</div>)
});
console.log(menu);
return (
<div>{menu}</div>
);
}
}
export default MainMenu;
Thank you in advance
// Dragoness
Updated 19 sep 2019 with solution
I got some tips from those links:
I changed my images folder to be in the public instead of in src:
getting broken image in React App
Started to see a pattern that most of the tables with an image inside have some kind of "name" column, at least it worked for me:
https://www.youtube.com/watch?v=lTyks6s6b6E
All my success steps I took:
Fixed:
1. I added a folder called images inside the public folder.
2. Added one image of the main menu that I called home.
3. Went to the SQL database, deleted the old rows I tried to display the
data from that you can see on the browse tab that was inside the table
menus.
4. Added another column called picName. Took it as a varchar with 60 in
lengh.
5. Changed the settings on the picUrl to be a varchar with the lengh of
255 instead of 100 that I had before.
6. I did a test using the insert tab selection to add a row with the image
link I had before with the dot dot slash and it worked!.
7. Added 15 more rows(all main and undermenu buttons with its data).
8. After that I changed the folder structure again to have images/Buttons
and added all the button images that I had inside the src folder before.
9. Deleted all the images that were on the old folder.
10. Fixed: App.js took away the import of the DropDownMenu.js component and that it didnt print out my DropDownMenu.js component anymore.
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import MainMenu from "./components/MainMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<MainMenu />
<p className="TEST"> lorem imsum </p>
<div><img src='./images/Buttons/main_menu_home.png'/> </div>
</div>
);
}
}
export default App;
I couldn´t add the images of how my SQL database look now instead of before/where I find my images now in what folder because am new in Stack Overflow and don´t have enough reputation apperely. But those above are the steps I took to solve my problem :)

Apanding external HTML to a react component is not working

Basically I want to add an static HTML to a react component from external script.
So I'm saving the reference of this to window variable as follows:
let { PropTypes } = React;
export default class Body extends React.Component {
constructor(){
super();
let frmTrgt={};
frmTrgt.refff=this;
console.log("tthis: ",this);
window.bdyRefrence=frmTrgt;
}
static defaultProps = {
items: []
};
static propTypes = {
items: PropTypes.array.isRequired
};
render() {
return (
<div className={styles.body}>
<h1 className={styles.header}>React Seed</h1>
<p>This is an example seed app, powered by React, ES6 & webpack.</p>
<p>Here is some example data:</p>
<Menu items={this.props.items} />
<div>
<h1>Dynamic Content</h1>
<div id="myDynamicContent"></div>
</div>
</div>
);
}
}
and in my script tag in INDEX.html( Outside Script) I'm doing like following:
function addPHtml() {
try {
window.bdyRefrence.refff.refs.formTarget.insertAdjacentHTML("<p id='mhere'>paragraph 2</p>");
}catch (err){
console.log("err: ",err);
}
}
but when I'm calling addPHtml it is giving following error:
err: TypeError: Cannot read property 'insertAdjacentHTML' of undefined
at addPHtml ((index):19)
at <anonymous>:1:1
What your trying to do is not the correct way to insert the element in React, still for you requirement please refer below mentioned code
Your render function should be like
return(
<div>
<div ref="formTarget"></div>
<h1 >React Seed</h1>
<p>This is an example seed app, powered by React, ES6 & webpack.</p>
<p>Here is some example data:</p>
<div>
<h1>Dynamic Content</h1>
<div id="myDynamicContent"></div>
</div>
</div>
)
Please check Demo here Demo
In case using new React syntax (Createclass is deprecated now) use
window.refferedItem.refs.formTarget.getDOMNode().insertAdjacentHTML

Cannot load data.json file using jQuery and React.js

I must say first that I come from mobile development. I am very new with web development so this is probably an amateur questions.
I am building a react.js project using create-react-app (which uses Babel). I am trying to follow a tutorial where I am supposed to import a *.json file when my component mounts. I can't seem to be able to access my data, and I get an error saying "filteredApts.map is not a function".
Here are my imports:
import React from 'react';
import './App.css';
import $ from 'jquery';
Here is my componentWillMount method:
componentDidMount: function() {
console.log($.get('./data.json', function(){}.bind(this))) //This seems to get an HTML Page returned!
this.serverRequest = $.get('./data.json', function(result) {
var tempApts = result;
this.setState({
myAppointments: tempApts
}); //setState
}.bind(this));
},
my render method:
render: function() {
var filteredApts = this.state.myAppointments;
filteredApts = filteredApts.map(function(item, index) {
return (<li className="pet-item media" key={index}>
<div className="pet-info media-body">
<div className="pet-head">
<span className="pet-name">{this.state.myAppointments[index].petName}</span>
<span className="apt-date pull right">{this.state.myAppointments[index].petName}</span>
</div>
<div className="owner-name"><span className="label-item">Owner:</span>
{this.state.myAppointments[index].ownerName}</div>
<div className="apt-notes">
{this.state.myAppointments[index].aptNotes}</div>
</div>
</li>)
}.bind(this));
return (<div className="interface">
<div className="item-list media-list">
<ul className="item-list media-list"></ul>
</div>
</div>)
} //render
}); //MainInterface
Here is my map of files:
And finally my console log:
Is somebody capable of pointing out what I might be doing wrong?
I'd suggest to change this line:
var filteredApts = this.state.myAppointments;
to this
var filteredApts = this.state.myAppointments || [];
You use asynchronous data fetching and at the moment of rendering it can be no myAppointments yet.
Looks like your responseText is html.
I figured it out.
First, './data.json' was pointing to the public folder by default.
Second, I was missing {filteredApts} in
return (<div className="interface">
<ul className="item-list media-list">{filteredApts}</ul>
</div>)
Thanks anyways to all.

Categories