Load from JSON using external API

Let’s take RandomUser.me API. Some code from this method we will use in next examples.

To get data from the website we will use the fetch() method, it’s the modern way to make http requests

but first things first, break down the component

line 5—11. props.userAmount —this is a cards counter (number controller) and with its help we could set the number of product cards we need to create.

state.json—React don’t have setProps(), so we will use setState() instead. We have to use setState only in React Lifecycle. Let’s call our state “json”.

interface Props {
usersAmount: number;
interface States {
json: any;

line 13. It’s our link, a place where a GET request will be sent. To define how many profiles we want to get, we will use query string ?results=number but the number we will set in the props object.

const dataURL = "https://randomuser.me/api/?results=";

line 17—25. Define default props, number of cards in particular. Also, we should create “json” state it should be an empty array.

static defaultProps = {
width: 375,
height: 600,
usersAmount: 3
state = {
json: []

line 27—35. Create a control. Max cards amount will be fifteen for example.

static propertyControls: PropertyControls<Props> = {
usersAmount: {
type: ControlType.Number,
max: 15,
min: 1,
step: 1,
title: "Amount"

line 37—42. The most important part in our code is the fetch() function. We will call this method in a few places in the component lifecycle.

In the function we will pass dataURL + this.props.usersAmount

fetchJSON(jsonPath) {
.then(response => response.json())
.then(data => this.setState({ json: data.results }));

line 46—56. As I mentioned we will use fetchJSON() in the component lifecycle methods — componentDidMount() and componentDidUpdate().

// We need this method for the very first time
// when we drag`n`drop our component from the left panel
componentDidMount() {
this.fetchJSON(dataURL + this.props.usersAmount);
// Compare previous and current Prop. If they are different
// we could make changes
componentDidUpdate(prevProps, prevState) {
if (prevProps.usersAmount !== this.props.usersAmount) {
this.fetchJSON(dataURL + this.props.usersAmount);

line 58–80. Render() method is the same as in the first example. Create a loop Object.map(), take keys name, email and picture from the fetched object.

Boom! Done!


Source link https://blog..io/use--data-in-framer-x-3801834e3f59?source=rss—-eb297ea1161a—4


Please enter your comment!
Please enter your name here