ReactJS/Reflux Converting mixins to ES6 - reactjs

I'm trying to convert the following Compenent to ES6, I already modified all the code for Store/Action, I can't figure out a solution to replace mixins and use normal ES6.
This is for a front end project, I'm just trying to parse JSON Data into components using Reflux.
import React from 'react';
import Reflux from 'reflux';
import {Jumbotron} from 'react-bootstrap';
import {Button} from 'react-bootstrap';
import {Link} from 'react-router';
import PopularActions from '../Actions/DragAction';
import PopularStore from '../Stores/DragStore';
import createReactClass from 'create-react-class';
const JSONViewerReflux = createReactClass({
//this is the part that I need in ES6
mixins: [Reflux.connect(PopularStore, 'DragStore')],
DragStore: null,
render() {
const store = this.DragStore ? this.DragStore : this.state.DragStore;
if(store) {
return (
<Jumbotron>
<h2>JSON Elements</h2>
{
store.map(({Name, Id}) => <div>
<h3>{Name} </h3>
<h3>{Id}</h3>
</div>)
}
</Jumbotron>
);
} else {
setTimeout(PopularActions.fetchPopular, 2000);
return <span />
}
}
});
export default JSONViewerReflux;
//Here is the store/action
import Reflux from 'reflux';
import $ from 'jquery';
import DragActions from '../Actions/DragAction';
const data = [];
function parseData(fetchedData) {
console.log(fetchedData);
const dragitemData = fetchedData.users;
const dragitem = dragitemData.map(({name, ID}) => {
return {
Name: name,
Id: ID
};
});
this.dragitem = dragitem;
this.trigger(this.dragitem);
}
const DragStore = Reflux.createStore({
listenables: [DragActions],
Url: 'https://api.myjson.com/bins/dvx65',
dragitem: [],
init() {
this.fetchPopular();
},
fetchPopular() {
const that = this;
$.ajax({
url: this.Url,
method: 'GET'
}).done(parseData.bind(this))
}
});
export default DragStore;
import Reflux from 'reflux';
const DragAction = Reflux.createActions([
'fetchPopular'
]);
export default DragAction;
It works but I just want it in ES6 like the rest of the project so I can use easily the {NAME} and {ID} with other components.

mixins are no longer supported in React.Component (ES6 and beyond).
Alternative is discussed in this post

Related

React With Redux Thunk and Apollo Graphql - How to access client.query?

This is my app.js
import React from 'react'
import { Provider } from 'react-redux'
import { View } from 'react-native'
import { createStore, applyMiddleware } from 'redux'
import ReduxThunk from 'redux-thunk'
import Reducers from './redux'
import Routes from './config/routes'
import { ApolloClient, HttpLink, InMemoryCache } from 'apollo-boost'
import { ApolloProvider } from 'react-apollo'
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: new HttpLink({
uri: '...',
}),
})
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
initialized: true
}
}
render() {
return (
<View style={{ flex: 1 }}>
<ApolloProvider client={client}>
<Provider store={store}>
<Routes />
</Provider>
</ApolloProvider>
</View>
)
}
}
const store = createStore(Reducers, {}, applyMiddleware(ReduxThunk))
export default App
Ok, so far...basic.
This will render the initial file of my route: welcome.js
import React from 'react'
import {...} from 'react-native'
import { Actions } from 'react-native-router-flux'
import style from './style'
import { connect } from "react-redux"
import gql from 'graphql-tag'
class Welcome extends React.Component {
constructor(props) {
const LOGIN_MUTATION = gql`
mutation {
login(
email:"test#test.com"
password:"1234"
) {token}
}
`
// Bellow will not work..I've no idea how to call the client that
// I set at <ApolloProvider client={client}>
client
.mutate({
mutation: LOGIN_MUTATION
})
.then(res => console.log(res))
.catch(err => console.log(err))
}
}
const mapStateToProps = state => (
{
}
)
export default connect(mapStateToProps,
{
})(Welcome)
So, the client was defined on my app.js that's apply the provider and inject the routes.
I'd like to know how to be capable to execute the client defined at app,js into welcome.js
It's highly recommended that you switch for the new React Hooks version, using them, you can simply write const client = useApolloClient() to get access to your client instance:
import { useApolloClient } from '#apollo/react-hooks';
const Welcome = () => {
const client = useApolloClient();
return <h1>Welcome</h1>;
}
And regarding the ApolloProvider, it is configured in the same manner was you did, except that you can import it directly from the hooks package too, i.e import { ApolloProvider } from '#apollo/react-hooks -- and you can remove the react-apollo therefore.
See more details about hooks here: https://www.apollographql.com/docs/react/hooks-migration/.
But in case you really want to stay using class components, you can do:
import { getApolloContext } from 'react-apollo';
class Welcome extends React.Component {
...
}
Welcome.contextType = getApolloContext();
And then you'll be able to access the client using this.context.client inside your class:
class Welcome extends React.Component {
render() {
console.log('client', this.context.client);
return ...;
}
}
Welcome.contextType = getApolloContext();
You can use ApolloConsumer in your component to get access to the client:
To access the client directly, create an ApolloConsumer component and provide a render prop function as its child. The render prop function will be called with your ApolloClient instance as its only argument.
e.g.
import React from 'react';
import { ApolloConsumer } from "react-apollo";
const WithApolloClient = () => (
<ApolloConsumer>
{client => "We have access to the client!" /* do stuff here */}
</ApolloConsumer>
);

How to use 'Inject' without decorator in Mobx with ReactJs

I wonder how to use Inject without decorator.
First, I made this as Store.
//Data/imagedb
import { decorate, observable } from 'mobx';
class imageStore {
list = {
keyword : 'yoyo',
}
}
decorate(imageStore, {
list: observable,
})
export default imageStore;
Second, I made this code to inject Store on it.
//components/Image
import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
class Image extends Component {
render() {
const onPut2 = {onPut};
return (
<div>
{onPut2}
</div>
);
}
}
export default inject(({ imSt }) => ({
onPut: imSt.list.keyword,
}))(observer(Image));
And finally, this is my last code.
The error is "Onput is not defined" in second code.
import React from 'react';
import Image from 'components/Image';
import { Provider } from 'mobx-react';
import imageStore from 'Data/imagedb'
const imSt = new imageStore();
const Home = () => {
return (
<div>
<Provider imSt={imSt}>
<Image />
</Provider>
</div>
);
};
export default Home;

I face this export error of Cookie using in react

I do have this code and I'm going to use Cookies for first time but I get error below , anyone who can help me to fix the problem ?
"ERROR I FACE : Attempted import error: 'react-cookie' does not contain a default export (imported as 'Cookie'). "
import React from 'react';
import ReactDom from 'react-dom';
import './App.css';
import CountDown from './CountDown';
import Basket from './Basket';
import Cookie from 'react-cookie'
class Products extends React.Component{
constructor(props){
super(props);
this.state={
order : []
}
this.shop = this.shop.bind(this);
}
prevstate = [];
`enter code here`shop(evt){
this.prevstate.push(evt.target.id);
this.setState({
order : this.prevstate
})
console.log(Cookie.get('selected'))
Cookie.set('selected' , this.props.cart , {path :' /'});
}
render(){
return(
<div className="prowrap">
{this.props.prolist.map((name) => (
<div className="pro" key={name.id} style={{border:"1px red
solid"}} >
<img src={name.image}/>
<p>{name.name}</p>
<p>{name.detail}</p>
<p className="countdown"><CountDown time={name.date}/></p>
<div className="price">{name.price} Euro</div>
<button className="shop" id={name.id} onClick={this.shop}>Add To
Cart</button>
</div>))}
<Basket cart={this.state.order} allpro={this.props.prolist}/>
</div>
)
}
}
export default Products;
The error is clear react-cookie doesn’t have default export so you cannot import it like
import Cookie from 'react-cookie';
You need to import it like below
import { Cookies } from 'react-cookie';
Also it's not Cookie but Cookies. You are importing it wrongly
When it is default export then you don’t use {} to import but if it is not default export then you use {} to import it.
You need to import like import { withCookies, Cookies } from 'react-cookie'; and then cookies.get('selected'), refer the code below
Read the package readme carefully.
// App.jsx
import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props) {
super(props);
const { cookies } = props;
this.state = {
name: cookies.get('name') || 'Ben'
};
}
handleNameChange(name) {
const { cookies } = this.props;
cookies.set('name', name, { path: '/' });
this.setState({ name });
}
render() {
const { name } = this.state;
return (
<div>
<NameForm name={name} onChange={this.handleNameChange.bind(this)} />
{this.state.name && <h1>Hello {this.state.name}!</h1>}
</div>
);
}
}
export default withCookies(App);

How do you update a component in React when new data arrives on a stream?

I'm using the electron-boilerplate and Kurt Weiberth's tutorials to create my first node.js native app. I was able to create the app in the tutorial and now I want to add a component that gets updated when new tweets are streamed in given a query.
To do this, I created Tweet, TweetStream, and TweetFeed components, below. This kind of works, but I keep getting an error
Warning: flattenChildren(...): Encountered two children with the same key, ###############. Child keys must be unique; when two children share a key, only the first child will be used.
There are no duplicates when I look at the state for tweets, so I'm not sure why React is encountering them. Have I put something in the wrong place? Putting the Twit stream in a Component doesn't feel right, but I'm not sure where else it could go. I'd like to be able to update the query at some point so it seems like it needs to respond to an event when the query is updated.
Tweet
import React, { Component } from 'react';
class Tweet extends Component {
render() {
return (<li>
{this.props.tweet}
</li>);
}
}
export default Tweet;
TweetStream
import React, { Component } from 'react';
import Tweet from './Tweet';
class TweetStream extends Component {
render() {
return (
<ul>
{
this.props.tweets.map((tweet) => {
return <Tweet key={tweet.id} tweet={tweet.text} />;
})
}
</ul>
);
}
}
export default TweetStream;
TweetFeed
import React, { Component } from 'react';
const express = require('express');
const Twit = require('twit');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
class TweetFeed extends Component {
handleTweet(tweet) {
this.state = {
id: tweet.id,
text: tweet.text
};
this.props.actions.addTweet(tweet);
}
render() {
const ts = this;
io.on('connection', function (socket) {
console.log('User connected. Socket id %s', socket.id);
socket.on('disconnect', function () {
console.log('User disconnected. %s. Socket id %s', socket.id);
});
});
const T = new Twit({
consumer_key: 'KEY',
consumer_secret: 'SECRET',
access_token: 'TOKEN',
access_token_secret: 'TOKEN_SECRET',
timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests.
});
const stream = T.stream('statuses/filter', { track: this.props.query });
stream.on('tweet', function (tweet) {
io.sockets.emit('tweet', tweet);
ts.handleTweet(tweet);
});
return (<div />);
}
}
export default TweetFeed;
Tweets Reducer
const initialTwitterState = [];
export default function reducer(state = initialTwitterState, action) {
switch (action.type) {
case 'ADD_TWEET':
return [{id: action.text.id, text: action.text.text}, ...state];
default:
return state;
}
}
These are called from a Home component
// #flow
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import React, {Component} from 'react';
import styles from './Home.css';
import TodoInput from './TodoInput';
import TweetStream from './TweetStream'
import TweetFeed from './TweetFeed'
import * as TodoActions from '../actions/todo';
import * as TwitterActions from '../actions/twitter';
class Home extends Component {
render() {
console.log(this.props)
return (
<div>
<TweetStream tweets={this.props.tweets} actions={this.props.tweet_actions}/>
<TweetFeed query={this.props.todos.query} tweets={this.props.tweets} todos={this.props.todos} actions={this.props.tweet_actions}/>
</div>
);
}
}
function mapStateToProps(state) {
return state;
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(TodoActions, dispatch),
tweet_actions: bindActionCreators(TwitterActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);

How to import from the database a list of companies in the live search?

import css from './SearchField.styl';
import React, { Component } from 'react';
import CN from 'classnames';
import CompanyList from 'Company/List/CompanyList';
import Autosuggest from 'react-autosuggest';
const suburbs = ['Cheltenham', 'Mill Park', 'Mordialloc', 'Nunawading'];
export default class SearchInput extends Component {
render() {
function getSuggestions(input, callback) {
const regex = new RegExp('^' + input, 'i');
const suggestions = suburbs.filter(suburb => regex.test(suburb));
setTimeout(() => callback(null, suggestions), 300); // Emulate API call
}
return (
<div className={CN(css.selectLive)}>
<Autosuggest suggestions={getSuggestions} />
</div>
);
}
};
I have a list of companies , a component
How do I connect to the live search ? I am new and it is impossible to connect the data from the database

Resources