Apr 24, 2020 08:58 AM
I am extracting a database of children’s books via Airtable API.
This is my code so far(hiding my API KEY). It renders every book, but in a random order. I want to sort them by year.
I am trying to follow the documentation from Airtable, which demonstrates the code to sort by multiple fields. I don’t really know where to place this code in my original code, and how to adapt it. Thanks for your help!
import Hero from '../components/Hero';
class News extends Component {
constructor(props) {
super(props);
this.state = {
books: [],
};
}
componentDidMount() {
fetch('https://api.airtable.com/v0/appYI3FvXw9Isfvj7/Favorites?api_key=API_KEY')
.then((resp) => resp.json())
.then(data => {
this.setState({ books: data.records });
}).catch(err => {
// Error :(
});
}
render() {
return (
<><Hero title="Children's Books"/>
<div className="container mt-5">
<div className="row">
<div className="col">
<div className="new-container">
{this.state.books.map(book => <BookCard {...book.fields} /> )}
</div>
</div>
</div>
</div>
</>
);
}
}
const BookCard = ({ imageURL, title, year, description, rating, date }) => (
<div className="card">
<img className="card-img-top" src={imageURL[0].url} alt="Book cover" />
<div className="card-body">
<h5 className="card-title"><strong>{title} ({year})</strong></h5>
<p className="card-text">
<small className="text-muted">{date}</small>
</p>
<p className="card-text">{description}</p>
<p className="card-text"><strong>Rating: {rating}/5</strong></p>
</div>
</div>
);
export default News;
Solved! Go to Solution.
Apr 24, 2020 02:55 PM
The documentation at http://airtable.com/api explains how to include a sort in your request.
It looks like you are sending a curl request. With curl, you need to append the sort query parameters to your url.
For example, if you want to sort by year, with the most recent ones first …
You can create an array of sort objects like this:
[ {field: "year", direction: "desc"} ]
Then convert it to strings that look like this:
sort[0][field]=year
sort[0][direction]=desc
Then url encode the strings:
sort%5B0%5D%5Bfield%5D=year
sort%5B0%5D%5Bdirection%5D=desc
Then append them to your url with ? and &
Apr 24, 2020 02:55 PM
The documentation at http://airtable.com/api explains how to include a sort in your request.
It looks like you are sending a curl request. With curl, you need to append the sort query parameters to your url.
For example, if you want to sort by year, with the most recent ones first …
You can create an array of sort objects like this:
[ {field: "year", direction: "desc"} ]
Then convert it to strings that look like this:
sort[0][field]=year
sort[0][direction]=desc
Then url encode the strings:
sort%5B0%5D%5Bfield%5D=year
sort%5B0%5D%5Bdirection%5D=desc
Then append them to your url with ? and &
Apr 27, 2020 08:26 AM
Thank you for your help! It’s what I needed!