facebook graph api images GraphRequest - image

I'm attempting to get the profile image of the user after logging in using FB graph. I'm getting a URL but no image
code:
async fetchProfile(callback) {
return new Promise((resolve, reject) => {
const request = new GraphRequest(
'/me',
{
parameters: { fields: { string: 'picture.width(480),name' } }
},
(error, result) => {
if (result) {
const profile = result
profile.avatar = `https://graph.facebook.com/${result.id}/picture`;
resolve(profile)
} else {
reject(error)
}
}
)
this.requestManager.addRequest(request).start()
})
}
}
response:
{
"avatar": "https://graph.facebook.com/4567877885493457976/picture",
"id": "4567877885493457976",
"name": "Billy Pope",
"picture": {
"data": {
"height": 389,
"is_silhouette": false,
"url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10219826402184549&width=480&ext=1588823752&hash=AeTZXPsxkrdi79ep",
"width": 480
}
}
}
How do I extract the image from either of these urls - avatar or url? Thanks

To display the image, I changed the view to look like:
{this.state.picture ? (
<Image
source={{ uri: this.state.picture }}
style={styles.imageStyle}
/>
) : null}
adding a condition along with height and width and the image suddenly appeared.

Related

Laravel Vue.js after patch request get doesn't load all the data

I want to dynamically hide the "Sign up" button when all the places for the event have been taken. I also update the list of signed-up users.
After clicking on the Signup button the data is saved correctly on the backend but the frontend displays only the pictures of players and there are the usernames. After refreshing the page I can see the usernames and photos. How can I fix my code so all the data will be displayed after the patch?
I'm using 2 Vue components:
AddPlayesComponent
<template>
<div>
<form v-if="freePlaces == true || freePlaces == 1" #submit.prevent="submit()">
<button type="submit" name="participant">Sign up</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
freePlaces: "",
url: "",
}
},
created() {
this.getUrl();
this.fetchStatus();
this.showForm();
},
methods: {
getUrl() {
let id = window.location.href.split('/').pop();
this.url = "/events/" + id + "/team" ;
},
fetchStatus() {
let id = window.location.href.split('/').pop();
axios.get('/events/'+ id + '/availabilty').then((response) => {
this.freePlaces = response.data;
})
},
showForm() {
Echo.channel('team-list-count')
.listen('.players-allowed', (data) => {
this.freePlaces = data.playersAllowed;
})
},
submit() {
axios.post(this.url, {
_method: 'patch'
})
.then(response => {
console.log(response.data);
})
.catch(e => {
console.log("Error is");
console.log(e.data);
});
}
},
computed: {
availabilePlaces() {
return this.freePlaces;
return this.url;
}
}
}
</script>
and TeamListComponent
<template>
<div>
<div v-for="(player, key) in team">
<img :src="'/storage/' + player.profil_photo" alt="profile picture " >
{{ player.username }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
team: [],
}
},
created() {
this.fetchTeam();
this.AddNewPlayerListener();
this.DeleteNewPlayerListener();
},
methods: {
fetchTeam() {
let id = window.location.href.split('/').pop();
axios.get('/events/'+ id + '/team').then((response) => {
this.team = response.data;
})
},
AddNewPlayerListener() {
Echo.channel('team-list')
.listen('.updated-team', (data) => {
this.team = data.team;
})
},
DeleteNewPlayerListener(){
Echo.channel('team-list-delete')
.listen('.updated-team', (data) => {
this.team = data.team;
})
}
},
computed: {
teamList() {
return this.team;
}
}
}
</script>
Controller contains this funcion:
protected function addPlayer($event) {
$registered = $event->registered_participants;
$registered++;
$allowed = $event->allowed_participants;
if($allowed <= $registered) {
$playersAllowed = false;
event(new ParticipantsCounter($playersAllowed));
if($allowed < $registered) {
return redirect()->route('event.show', [ 'event' => $event ]);
}
}
$event->registered_participants = $registered;
$event->save();
$profile = auth()->user()->profile;
$profile->participate()->syncWithoutDetaching([$event->id], false);
$team = $event->participants()->get();
foreach ($team as $player) {
$user = User::where('id', $player->user_id)->first();
$player->username = $user->username;
}
event(new NewParticipant($team));
return redirect()->route('event.show', [ 'event' => $event ]);
}
Data after patch request:
{ "id": 5,
"created_at": "2022-04-12T20:35:03.000000Z",
"updated_at": "2022-04-12T20:35:40.000000Z",
"user_id": 5,
"name": "Marlena",
"familyname": "Test",
"location": "Amblève",
"gender": "x",
"birthdate": "2000-12-12",
"favorite_sport": "hockey",
"biography": "Here comes biography",
"profil_photo": "profiles/kbERb4XrXnu379rtCcyWwb46pOq9UQAtkTKgr42W.jpg" }
Data after refreshing page:
{ "id": 5,
"created_at": "2022-04-12T20:35:03.000000Z",
"updated_at": "2022-04-12T20:35:40.000000Z",
"user_id": 5,
"name": "Marlena",
"familyname": "Test",
"location": "Amblève",
"gender": "x",
"birthdate": "2000-12-12",
"favorite_sport": "hockey",
"biography": "Here comes biography",
"profil_photo": "profiles/kbERb4XrXnu379rtCcyWwb46pOq9UQAtkTKgr42W.jpg",
"username": "testUser",
"pivot": {
"event_id": 1,
"profile_id": 5,
"created_at": "2022-04-25T15:27:37.000000Z",
"updated_at": "2022-04-25T15:27:37.000000Z" }
}
Update:
I solved it by creating an empty array where I push each player after adding a username.
$oldTeam = $event->participants()->get();
$team = [];
foreach ($oldTeam as $player) {
$user = User::where('id', $player->user_id)->first();
$player->username = $user->username;
array_push($team, $player);
}

Apollo client's offsetLimitPagination requests for graphql server although the data is available in cache

Whenever I navigate to different pages, data will be added to Apollo's cache. but when I navigate to previous pages, although the data is available in cache. Apollo issues a network request to graphql server.
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
users: {
...offsetLimitPagination(),
read(existing, { args }) {
return (
existing &&
existing.slice(
args?.offset,
args?.offset + args?.limit
)
)
},
}
},
},
},
})
const client = new ApolloClient({
uri: "https://api.spacex.land/graphql/",
cache,
connectToDevTools: true,
})
And my component:
const Users: React.FC = () => {
const [offset, setOffset] = useState(0)
const { loading, data, error, fetchMore } = useUsersQuery({ \\ Generated via graphql-code-gen
variables: { offset, limit: 2 },
})
const fetchMoreHandler = (): void => {
const currentLength = data?.users.length || 0
fetchMore({
variables: { offset: offset + currentLength, limit: 2 },
}).then(() => {
setOffset((ofsset) => ofsset + currentLength)
})
}
const fetchPrevHandler = (): void => {
let currentLength = data?.users.length || 0
if (currentLength === 0) {
currentLength = 2
}
fetchMore({
variables: { offset: offset - currentLength, limit: 2 },
}).then(() => {
setOffset((ofsset) => ofsset - currentLength)
})
}
if (loading) {
return <div>Loading....</div>
}
if (error) {
return <div>Something went wrong!</div>
}
return (
<div className={classes.root}>
{offset > 0 && (
<button type="button" onClick={fetchPrevHandler}>
Prev
</button>
)}
<div>
{data?.users.map((user) => (
<div key={user.id}>
<h6>{user.name}</h6>
</div>
))}
</div>
{(data?.users.length || 0) > 0 && (
<button type="button" onClick={fetchMoreHandler}>
Next
</button>
)}
</div>
)
}
export default Users
And here's the query:
query Users($offset: Int, $limit: Int) {
users(offset:$offset, limit: $limit, order_by:[{timestamp:desc}]) {
id
name
rocket
timestamp
twitter
}
}
When I navigate my cache looks like this:
_APOLLO_CLIENT_.cache.data.data:
{
"users:a75bf714-30e4-4219-8335-e413f8f127ef": {
"id": "a75bf714-30e4-4219-8335-e413f8f127ef",
"__typename": "users",
"name": "HI",
"rocket": "FRIENDS",
"timestamp": "2021-12-22T18:38:09.805832+00:00",
"twitter": null
},
"users:c2317843-8481-4cb6-87e1-16d8f4aa7092": {
"id": "c2317843-8481-4cb6-87e1-16d8f4aa7092",
"__typename": "users",
"name": "simeooone",
"rocket": "tha_rocket",
"timestamp": "2021-12-22T16:14:50.431972+00:00",
"twitter": "#galfh"
},
"ROOT_QUERY": {
"__typename": "Query",
"users": [
{
"__ref": "users:a75bf714-30e4-4219-8335-e413f8f127ef"
},
{
"__ref": "users:c2317843-8481-4cb6-87e1-16d8f4aa7092"
},
{
"__ref": "users:f6358c49-7ce3-491e-8103-48e9e4b847cd"
},
{
"__ref": "users:a04c9b78-3406-4585-ba16-0a4c540fdc23"
}
]
},
"users:f6358c49-7ce3-491e-8103-48e9e4b847cd": {
"id": "f6358c49-7ce3-491e-8103-48e9e4b847cd",
"__typename": "users",
"name": "aemilio",
"rocket": "yo_mum",
"timestamp": "2021-12-22T16:11:14.728876+00:00",
"twitter": "#yo_mum"
},
"users:a04c9b78-3406-4585-ba16-0a4c540fdc23": {
"id": "a04c9b78-3406-4585-ba16-0a4c540fdc23",
"__typename": "users",
"name": "",
"rocket": "oy",
"timestamp": "2021-12-22T16:10:24.420815+00:00",
"twitter": "asd"
}
}
And when I navigate back to show these exact items, still apollo makes network requests!
For other's that are new to Apollo like me and have this question, I figured out that fetchMore function always force network request no matter what. That's by design. If you want to read from cache you shouldn't use fetchMore and do something like this instead:
const [offset, setOffset] = useState(0)
const { loading, data, error } = useUsersQuery({
variables: { offset, limit: 2 },
})
const fetchMoreHandler = (): void => {
const currentLength = data?.users.length || 0
setOffset((ofsset) => ofsset + currentLength)
}
const fetchPrevHandler = (): void => {
let currentLength = data?.users.length || 0
if (currentLength === 0) {
currentLength = 2
}
setOffset((ofsset) =>
ofsset - currentLength < 0 ? 0 : ofsset - currentLength
)
}
and this would be your instance of InMemoryCache:
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
users: {
...offsetLimitPagination(),
read(existing, { args }) {
let res
if (existing) {
res = existing.slice(
args?.offset,
args?.offset + args?.limit
)
}
return res && res.length === args?.limit
? res
: undefined
},
},
},
},
},
})

facing problem in vue apexchart dynamic data set from api

I am try to create vue barchart & using apexChartData.
Here is my code
export default{
components: {
VueApexCharts
},
data () {
return {
barChart: {
series: [{
data: []
}],
chartOptions: {
plotOptions: {
bar: {
horizontal: true
}
},
dataLabels: {
enabled: false
},
xaxis: {
categories: []
}
}
}
},
methods: {
myFunction() {
this.$vs.loading();
axios.get("/api/auth/nameofapi").then(response => {
this.barChart.series[0].data = response.data[0]['data'];
this.barChart.chartOptions.xaxis.categories = response.data[1]['categories'];
this.$vs.loading.close();
}).catch(error => {
this.$vs.loading.close()
this.errorResponse(error);
});
}
},
mounted () {
this.myFunction();
}
}
My API Response payload like
[{"data":[4,1]},{"categories":["xyz","abc"]}]
After doing this bar chart is not loading, i am not sure where i am doing mistake, sorry for repeating this post if already exist but i just post what i am facing.
Any Help
Thanks in advance

Image source from state attribute

So I have this database:
[
{
"url": "https://i.imgur.com/5UzmND6.png",
"idEquipo": 4
},
{
"url": "https://i.imgur.com/yNj4w3b.jpg",
"idEquipo": 3
},
{
"url": "https://i.imgur.com/410yDrl.png",
"idEquipo": 1
},
{
"url": "https://i.imgur.com/Qv4S7p7.png",
"idEquipo": 2
},
{
"url": "https://drive.google.com/file/d/1RKsZuCqlheKnuu5yf-6MLoct_SDqX6we/view",
"idEquipo": 5
}
]
I want to use the state "imagen" as my image source.
This is my fetch:
getImagenes(id) {
fetch(Global.url + "Imagenes?idEquipo=" + id)
.then(res => res.json())
.then(res => {
this.setState({
imagen: res,
isLoading: false,
});
});
}
To be clear, fetch(Global.url + "Imagenes?idEquipo=" + id) returns this:
[
{
"url": "https://i.imgur.com/410yDrl.png",
"idEquipo": 1
}
]
So I want to get access to the url and use it as the source of my image.
This is my code, but it doesnt work. It's the first time I use uri, i'm a student.
<View style={styles.app_LogoContainer}>
<Image source={{uri: this.state.imagen.url}}
style={styles.image}></Image>
</View>
How can I do this? Thanks for the help
It's not clear to me that you have an object or an array with a single item. Did you try with imagen[0].url?

Transforming object data to array for d3plus-react

I have an api that returns data in the following format:
{
"Information Technology": {
"Name": "Information Technology",
"Change": "0.82%"
},
"Consumer Staples": {
"Name": "Consumer Staples",
"Change": "0.19%"
}
}
I want to convert it to the following format inside my d3plus visualizations:
[
{
"Name": "Information Technology",
"Change": "0.82%"
},
{
"Name": "Consumer Staples",
"Change": "0.19%"
}
]
How do I do this. Here's my React component that uses d3plus:
function Chart() {
const methods = {
groupBy: 'Name',
data: 'https://example.com/api/sectors-performance',
size: d => d.Change
};
return <Treemap config={methods} />;
}
There was a small hint in the docs which helped me come up with this solution:
function Chart() {
const methods = {
groupBy: 'id',
data: 'https://example.com/api/sectors-performance',
size: d => d.value
};
const formatter = d =>
Object.keys(d).map(key => ({
id: d[key].Name,
value: numeral(d[key].Change).value()
}));
return <Treemap config={methods} dataFormat={formatter} />;
}
The trick is to send a formatter as a property!

Resources