Skip to content

Instantly share code, notes, and snippets.

@miguelpeixe
Last active November 9, 2017 10:36
Show Gist options
  • Save miguelpeixe/41e52fb2a86a5893b9d00473441c1d20 to your computer and use it in GitHub Desktop.
Save miguelpeixe/41e52fb2a86a5893b9d00473441c1d20 to your computer and use it in GitHub Desktop.
React Axios Search Example
# On backend
app.use('/searchInterests', function(req, res) {
const token = app.get('fbAppToken');
if(req.query.q) {
app.facebook.api('search', {
type: 'adinterest',
q: req.query.q,
access_token: token,
locale: 'en_US'
}).then(function(data) {
res.send(data);
}).catch(function(err) {
res.send(err);
});
} else {
res.send({});
}
});
import React, { Component } from 'react';
import styled from 'styled-components';
import axios from 'axios';
const TableWrapper = styled.table`
width: 100%;
margin: 0 auto;
`
const Form = styled.form`
input {
width: 100%;
display: block;
font-size: 1.4em;
margin-bottom: 2rem;
}
`
class Table extends Component {
render () {
const { items } = this.props;
if(Array.isArray(items) && items.length) {
return (
<TableWrapper>
<thead>
<tr>
<th># ID</th>
<th>Name</th>
<th>Size</th>
<th>Paths</th>
<th>Description</th>
<th>Topic</th>
</tr>
</thead>
<tbody>
{items.map((item, i) => (
<tr key={i}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.audience_size}</td>
<td>{item.path.join(', ')}</td>
<td>{item.description}</td>
<td>{item.topic}</td>
</tr>
))}
</tbody>
</TableWrapper>
)
} else {
return null;
}
}
}
class SearchInterests extends Component {
constructor (props) {
super(props);
this.search = this.search.bind(this);
this.handleChange = this.handleChange.bind(this);
this.state = {
formData: {},
};
}
search (ev) {
ev.preventDefault();
const { formData } = this.state;
axios.get(`/searchInterests?q=${formData.search}`).then(res => {
if(res.data.data) {
this.setState({
items: res.data.data
});
} else {
this.setState({
items: []
});
}
});
}
handleChange (ev) {
const { formData } = this.state;
const { target } = ev;
const value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({
formData: Object.assign({}, formData, {[target.name]: value})
});
}
render () {
const { items } = this.state;
return (
<div id="search" className="content">
<Form onSubmit={this.search}>
<input type="text" name="search" placeholder="Search an interest" onChange={this.handleChange} />
</Form>
<Table items={items} />
</div>
)
}
}
export default SearchInterests;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment